Search code examples
azureazure-bicepapim

Bicep API Management: issue with creating operations policy with backend


I am having an issue integrating an API Operation with a Backend in a bicep file. Here is the snippet of code:

    resource MobileApiOperationGetHeartbeatPolicy 'Microsoft.ApiManagement/service/apis/operations/policies@2020-12-01' = {
      name: 'policy'
      parent: MobileApiOperationGetHeartbeat
      properties: {
        value: '<policies><inbound><base/><set-backend-service base-url="@(backend.properties.url)" /></inbound><backend><base/></backend><outbound><base/></outbound><on-error><base/></on-error></policies>'
        format: 'rawxml'
      }
    }

I constantly get this error:

{"code":"ValidationError","message":"One or more fields contain incorrect values:","details":[{"code":"ValidationError","target":"set-backend-service","message":"Error in element 'set-backend-service' on line 1, column 28: The name 'backend' does not exist in the current context"}]}

The APIM backend (called: backend) is created (successfully) up in the same file.

I tried with backend-id, I tried passing this via a variable, always get the same error.

If I replace the value of base-url with a hardcoded value it works. But I need to pass this via the backend, as I intend to switch the backend later on, without going to change all the operations (there might be hundreds of them). At the very least, need to pass this via a variable.

I have a feeling this may be some formatting issue, but I dont know how to get it to work.


Solution

  • Error is happening because evaluation of @(backend.properties.url) is failing.

    There is no such variable as backend in this context.


    Policy to set a backend service works differently.

    There are two options to use <set-backend-service />:

    1. Either you set the URL:

      <set-backend-service base-url="https://contoso.com/api/8.2/" />
      

      You can use an APIM Named Value instead of a hardcoded URL. The Named Value must exist, otherwise policy will be failed to be created.

      For example, you can use {{contoso-api-url}} instead of https://contoso.com/api/8.2/.

    2. Or you set the backend by ID:

      <set-backend-service backend-id="contoso-api" />
      

      In this example, contoso-api is the ID of the existing APIM backend that you want to use.

    Microsoft Learn: Azure / API Management / Set backend service:

    https://learn.microsoft.com/en-us/azure/api-management/set-backend-service-policy