DEV Community

Lord Jake
Lord Jake

Posted on

How to Enable CORS for API Management Development Portal using Terraform

Today I got a task to automate the Enable CORS feature in the Portal Overview of Developer Portal in Azure API Management Services.

Image description

This can be achived either via azure_rm or az_api according to documentations. I used azure_rm to achieve this.

We would need to create a policy file with CORS definitions and refer the file to the terraform configurations.

Policy file will look as below.

<policies>  
    <inbound>    
        <cors allow-credentials="true">      
            <allowed-origins>        
                <origin>https://example-apim-19899.developer.azure-api.net</origin>      
            </allowed-origins>      
            <allowed-methods preflight-result-max-age="300">        
                <method>*</method>      
            </allowed-methods>      
            <allowed-headers>        
                <header>*</header>      
            </allowed-headers>      
            <expose-headers>        
                <header>*</header>      
            </expose-headers>    
        </cors>  
    </inbound>  
    <backend>    
        <forward-request />  
    </backend>  
    <outbound />
</policies>

Enter fullscreen mode Exit fullscreen mode

Terraform code can be created as below to use the policy.

resource "azurerm_resource_group" "example" {
  name     = "example-resources"
  location = "uksouth"
}

resource "azurerm_api_management" "example" {
  name                = "example-apim-19899"
  location            = azurerm_resource_group.example.location
  resource_group_name = azurerm_resource_group.example.name
  publisher_name      = "pub1"
  publisher_email     = "pub1@email.com"

  sku_name = "Developer_1"
}

resource "azurerm_api_management_policy" "example" {
  api_management_id = azurerm_api_management.example.id
  xml_content       = file("\\policy_files\\example.xml")
}
Enter fullscreen mode Exit fullscreen mode

On running Terraform, the policies should be set and CORS should be enabled. Please make sure you give the origin in the policy file as the developer portal URL so that Azure correctly match it and it gets enabled in portal.

If you need to try using AzApi further details can be found here.
https://learn.microsoft.com/en-us/azure/templates/microsoft.apimanagement/service/policies?pivots=deployment-language-terraform

Top comments (0)