部署 XML 策略到 APIM 使用 Bicep。

huangapple go评论56阅读模式
英文:

deploying xml policy to apim using bicep

问题

我想将以下策略部署到Azure API管理:

```xml
<policies>
    <inbound>
    <base />
    <choose>
        <when condition="@(!context.Variables.ContainsKey('cachedAccessToken') || DateTime.UtcNow >= (DateTime)context.Variables['tokenExpiry'])">
            <set-backend-service id="apim-generated-policy" backend-id="{0}" />
            <send-request mode="new" response-variable-name="tokenResponse" timeout="20" ignore-error="false">
                <set-url>{1}/token</set-url>
                <set-method>POST</set-method>
                <set-header name="Content-Type" exists-action="override">
                    <value>application/x-www-form-urlencoded</value>
                </set-header>
                <set-body>@("grant_type=password&username={2}&password=thisShouldRefThe-AmxPassword-NamedValue")</set-body>
            </send-request>
            <set-variable name="tokenResponseJson" value="@{{ return JsonConvert.DeserializeObject((string)context.Variables['tokenResponse'].Body.As<string>()); }}" />
            <set-variable name="cachedAccessToken" value="@{{(string)context.Variables['tokenResponseJson']['access_token']}}" />
            <set-variable name="tokenExpiry" value="@{{ return DateTime.UtcNow.AddSeconds((int)context.Variables['tokenResponseJson']['expires_in'] - 60); }}" />
            <cache-store-value key="cachedAccessToken" value="@{{context.Variables['cachedAccessToken']}}" duration="@{{(new TimeSpan(0, (int)context.Variables['tokenResponseJson']['expires_in'], 0))}}" />
            <cache-store-value key="tokenExpiry" value="@{{context.Variables['tokenExpiry']}}" duration="@{{(new TimeSpan(0, (int)context.Variables['tokenResponseJson']['expires_in'], 0))}}" />
        </when>
        <otherwise>
            <cache-lookup-value key="cachedAccessToken" variable-name="cachedAccessToken" />
            <cache-lookup-value key="tokenExpiry" variable-name="tokenExpiry" />
        </otherwise>
    </choose>
    <set-header name="Authorization" exists-action="override">
        <value>@{{$"Bearer {{context.Variables['cachedAccessToken']}}}}</value>
    </set-header>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

这是由DevOps管道运行的Bicep代码:

resource apim 'Microsoft.ApiManagement/service@2022-04-01-preview' existing = {
    name: apimName

    resource apiVersionSet 'api-version-sets@2018-06-01-preview' = if (enableApiVersioning) {
        name: apiName
        properties: {
            displayName: displayName
            versioningScheme: versionScheme
            versionHeaderName: 'X-Api-Version'
            versionQueryName: 'api-version'
        }
    }

    resource api 'apis' = {
        name: enableApiVersioning ? apiNameVersioned : apiName
        properties: {
            displayName: displayName
            path: '${pathPrefix}${apiName}'
            format: definitionFormat
            protocols: [
                'https'
            ]
            subscriptionRequired: true
            value: definition
            apiVersion: enableApiVersioning ? version : null
            apiVersionSetId: enableApiVersioning ? apiVersionSet.id : null
            subscriptionKeyParameterNames: {
                header: 'Ocp-Apim-Subscription-Key'
                query: 'subscription-key'
            }
        }

        resource apiPolicy 'policies' = if (!empty(policy)) {
            name: 'policy'
            properties: {
                value: policy
            }
        }
    }
}

我收到以下错误:

'='是意外的标记。预期的标记是';'。第13行,位置58。


<details>
<summary>英文:</summary>

I&#39;d like to deploy the following policy to azure api management:

````xml
&lt;policies&gt;
    &lt;inbound&gt;
    &lt;base /&gt;
    &lt;choose&gt;
        &lt;when condition=&quot;@(!context.Variables.ContainsKey(&#39;&#39;cachedAccessToken&#39;&#39;) || DateTime.UtcNow &gt;= (DateTime)context.Variables[&#39;&#39;tokenExpiry&#39;&#39;])&quot;&gt;
            &lt;set-backend-service id=&quot;apim-generated-policy&quot; backend-id=&quot;{0}&quot; /&gt;
            &lt;send-request mode=&quot;new&quot; response-variable-name=&quot;tokenResponse&quot; timeout=&quot;20&quot; ignore-error=&quot;false&quot;&gt;
                &lt;set-url&gt;{1}/token&lt;/set-url&gt;
                &lt;set-method&gt;POST&lt;/set-method&gt;
                &lt;set-header name=&quot;Content-Type&quot; exists-action=&quot;override&quot;&gt;
                    &lt;value&gt;application/x-www-form-urlencoded&lt;/value&gt;
                &lt;/set-header&gt;
                &lt;set-body&gt;@(&quot;grant_type=password&amp;username={2}&amp;password=thisShouldRefThe-AmxPassword-NamedValue&quot;)&lt;/set-body&gt;
            &lt;/send-request&gt;
            &lt;set-variable name=&quot;tokenResponseJson&quot; value=&quot;@{{ return JsonConvert.DeserializeObject((string)context.Variables[&#39;&#39;tokenResponse&#39;&#39;].Body.As&lt;string&gt;()); }}&quot; /&gt;
            &lt;set-variable name=&quot;cachedAccessToken&quot; value=&quot;@{{(string)context.Variables[&#39;&#39;tokenResponseJson&#39;&#39;][&#39;&#39;access_token&#39;&#39;]}}&quot; /&gt;
            &lt;set-variable name=&quot;tokenExpiry&quot; value=&quot;@{{ return DateTime.UtcNow.AddSeconds((int)context.Variables[&#39;&#39;tokenResponseJson&#39;&#39;][&#39;&#39;expires_in&#39;&#39;] - 60); }}&quot; /&gt;
            &lt;cache-store-value key=&quot;cachedAccessToken&quot; value=&quot;@{{context.Variables[&#39;&#39;cachedAccessToken&#39;&#39;]}}&quot; duration=&quot;@{{(new TimeSpan(0, (int)context.Variables[&#39;&#39;tokenResponseJson&#39;&#39;][&#39;&#39;expires_in&#39;&#39;], 0))}}&quot; /&gt;
            &lt;cache-store-value key=&quot;tokenExpiry&quot; value=&quot;@{{context.Variables[&#39;&#39;tokenExpiry&#39;&#39;]}}&quot; duration=&quot;@{{(new TimeSpan(0, (int)context.Variables[&#39;&#39;tokenResponseJson&#39;&#39;][&#39;&#39;expires_in&#39;&#39;], 0))}}&quot; /&gt;
        &lt;/when&gt;
        &lt;otherwise&gt;
            &lt;cache-lookup-value key=&quot;cachedAccessToken&quot; variable-name=&quot;cachedAccessToken&quot; /&gt;
            &lt;cache-lookup-value key=&quot;tokenExpiry&quot; variable-name=&quot;tokenExpiry&quot; /&gt;
        &lt;/otherwise&gt;
    &lt;/choose&gt;
    &lt;set-header name=&quot;Authorization&quot; exists-action=&quot;override&quot;&gt;
        &lt;value&gt;@{{$&quot;Bearer {{context.Variables[&#39;&#39;cachedAccessToken&#39;&#39;]}}&quot;}}&lt;/value&gt;
    &lt;/set-header&gt;
    &lt;/inbound&gt;
    &lt;backend&gt;
        &lt;base /&gt;
    &lt;/backend&gt;
    &lt;outbound&gt;
        &lt;base /&gt;
    &lt;/outbound&gt;
    &lt;on-error&gt;
        &lt;base /&gt;
    &lt;/on-error&gt;
&lt;/policies&gt;

This is the bicep that gets run by a devops pipeline:

resource apim &#39;Microsoft.ApiManagement/service@2022-04-01-preview&#39; existing = {
    name: apimName

    resource apiVersionSet &#39;api-version-sets@2018-06-01-preview&#39; = if (enableApiVersioning) {
        name: apiName
        properties: {
            displayName: displayName
            versioningScheme: versionScheme
            versionHeaderName: &#39;X-Api-Version&#39;
            versionQueryName: &#39;api-version&#39;
        }
    }

    resource api &#39;apis&#39; = {
        name: enableApiVersioning ? apiNameVersioned : apiName
        properties: {
            displayName: displayName
            path: &#39;${pathPrefix}${apiName}&#39;
            format: definitionFormat
            protocols: [
                &#39;https&#39;
            ]
            subscriptionRequired: true
            value: definition
            apiVersion: enableApiVersioning ? version : null
            apiVersionSetId: enableApiVersioning ? apiVersionSet.id : null
            subscriptionKeyParameterNames: {
                header: &#39;Ocp-Apim-Subscription-Key&#39;
                query: &#39;subscription-key&#39;
            }
        }

        resource apiPolicy &#39;policies&#39; = if (!empty(policy)) {
            name: &#39;policy&#39;
            properties: {
                value: policy
            }
        }
    }
}

I get the following error:

> '=' is an unexpected token. The expected token is ';'. Line 13, position 58.

答案1

得分: 1

以下是您要翻译的内容:

"Lesson learned - pay more attention to what chatgpt pumps out!

The main problem was the syntax for the C# code block. Here's the working policy:

&lt;policies&gt;
    &lt;inbound&gt;
    &lt;base /&gt;
    &lt;choose&gt;
        &lt;when condition=&quot;@(!context.Variables.ContainsKey(&quot;cachedAccessToken&quot;) || DateTime.UtcNow &gt;= (DateTime)context.Variables[&quot;tokenExpiry&quot;])&quot;&gt;
            &lt;set-backend-service id=&quot;apim-generated-policy&quot; backend-id=&quot;func-amx-api-dev-001&quot; /&gt;
            &lt;send-request mode=&quot;new&quot; response-variable-name=&quot;tokenResponse&quot; timeout=&quot;20&quot; ignore-error=&quot;false&quot;&gt;
                &lt;set-url&gt;{{baseurl}}.azurewebsites.net/token&lt;/set-url&gt;
                &lt;set-method&gt;POST&lt;/set-method&gt;
                &lt;set-header name=&quot;Content-Type&quot; exists-action=&quot;override&quot;&gt;
                    &lt;value&gt;application/x-www-form-urlencoded&lt;/value&gt;
                &lt;/set-header&gt;
                &lt;set-body&gt;@(&quot;grant_type=password&amp;username={{user}}&amp;password={{AmxPassword}}&quot;)&lt;/set-body&gt;
            &lt;/send-request&gt;
            &lt;set-variable name=&quot;cachedAccessToken&quot; value=&quot;@((String)((IResponse)context.Variables[&quot;jwt&quot;]).Body.As&lt;JObject&gt;()[&quot;access_token&quot;])&quot; /&gt;
            &lt;set-variable name=&quot;tokenExpiry&quot; value=&quot;@((String)((IResponse)context.Variables[&quot;jwt&quot;]).Body.As&lt;JObject&gt;()[&quot;expires_in&quot;])&quot; /&gt;
            &lt;cache-store-value key=&quot;cachedAccessToken&quot; value=&quot;@((String)context.Variables[&quot;cachedAccessToken&quot;])&quot; duration=&quot;3600&quot; caching-type=&quot;internal&quot; /&gt;
            &lt;cache-store-value key=&quot;tokenExpiry&quot; value=&quot;@((String)context.Variables[&quot;tokenExpiry&quot;])&quot; duration=&quot;3600&quot; caching-type=&quot;internal&quot; /&gt;
        &lt;/when&gt;
        &lt;otherwise&gt;
            &lt;cache-lookup-value key=&quot;cachedAccessToken&quot; variable-name=&quot;cachedAccessToken&quot; /&gt;
            &lt;cache-lookup-value key=&quot;tokenExpiry&quot; variable-name=&quot;tokenExpiry&quot; /&gt;
        &lt;/otherwise&gt;
    &lt;/choose&gt;
    &lt;set-header name=&quot;Authorization&quot; exists-action=&quot;override&quot;&gt;
        &lt;value&gt;@{
                return $&quot;Bearer {(String)context.Variables[&quot;cachedAccessToken&quot;]}&quot;;
            }&lt;/value&gt;
    &lt;/set-header&gt;
    &lt;/inbound&gt;
    &lt;backend&gt;
        &lt;base /&gt;
    &lt;/backend&gt;
    &lt;outbound&gt;
        &lt;base /&gt;
    &lt;/outbound&gt;
    &lt;on-error&gt;
        &lt;base /&gt;
    &lt;/on-error&gt;
&lt;/policies&gt;

I also moved the policy to a separate file and deployed at apim operation level with the following bicep:

resource apiPolicy &#39;Microsoft.ApiManagement/service/apis/operations/policies@2022-09-01-preview&#39; = {
    name: &#39;${apimName}/amxapi_v1_0_0/entity/policy&#39;
    properties: {
        value: loadTextContent(&#39;./createEntityPolicy.xml&#39;)
    }
}
英文:

Lesson learned - pay more attention to what chatgpt pumps out!

The main problem was the syntax for the C# code block. Here's the working policy:

&lt;policies&gt;
    &lt;inbound&gt;
    &lt;base /&gt;
    &lt;choose&gt;
        &lt;when condition=&quot;@(!context.Variables.ContainsKey(&quot;cachedAccessToken&quot;) || DateTime.UtcNow &gt;= (DateTime)context.Variables[&quot;tokenExpiry&quot;])&quot;&gt;
            &lt;set-backend-service id=&quot;apim-generated-policy&quot; backend-id=&quot;func-amx-api-dev-001&quot; /&gt;
            &lt;send-request mode=&quot;new&quot; response-variable-name=&quot;tokenResponse&quot; timeout=&quot;20&quot; ignore-error=&quot;false&quot;&gt;
                &lt;set-url&gt;{{baseurl}}.azurewebsites.net/token&lt;/set-url&gt;
                &lt;set-method&gt;POST&lt;/set-method&gt;
                &lt;set-header name=&quot;Content-Type&quot; exists-action=&quot;override&quot;&gt;
                    &lt;value&gt;application/x-www-form-urlencoded&lt;/value&gt;
                &lt;/set-header&gt;
                &lt;set-body&gt;@(&quot;grant_type=password&amp;username={{user}}&amp;password={{AmxPassword}}&quot;)&lt;/set-body&gt;
            &lt;/send-request&gt;
            &lt;set-variable name=&quot;cachedAccessToken&quot; value=&quot;@((String)((IResponse)context.Variables[&quot;jwt&quot;]).Body.As&lt;JObject&gt;()[&quot;access_token&quot;])&quot; /&gt;
            &lt;set-variable name=&quot;tokenExpiry&quot; value=&quot;@((String)((IResponse)context.Variables[&quot;jwt&quot;]).Body.As&lt;JObject&gt;()[&quot;expires_in&quot;])&quot; /&gt;
            &lt;cache-store-value key=&quot;cachedAccessToken&quot; value=&quot;@((String)context.Variables[&quot;cachedAccessToken&quot;])&quot; duration=&quot;3600&quot; caching-type=&quot;internal&quot; /&gt;
            &lt;cache-store-value key=&quot;tokenExpiry&quot; value=&quot;@((String)context.Variables[&quot;tokenExpiry&quot;])&quot; duration=&quot;3600&quot; caching-type=&quot;internal&quot; /&gt;
        &lt;/when&gt;
        &lt;otherwise&gt;
            &lt;cache-lookup-value key=&quot;cachedAccessToken&quot; variable-name=&quot;cachedAccessToken&quot; /&gt;
            &lt;cache-lookup-value key=&quot;tokenExpiry&quot; variable-name=&quot;tokenExpiry&quot; /&gt;
        &lt;/otherwise&gt;
    &lt;/choose&gt;
    &lt;set-header name=&quot;Authorization&quot; exists-action=&quot;override&quot;&gt;
        &lt;value&gt;@{
                return $&quot;Bearer {(String)context.Variables[&quot;cachedAccessToken&quot;]}&quot;;
            }&lt;/value&gt;
    &lt;/set-header&gt;
    &lt;/inbound&gt;
    &lt;backend&gt;
        &lt;base /&gt;
    &lt;/backend&gt;
    &lt;outbound&gt;
        &lt;base /&gt;
    &lt;/outbound&gt;
    &lt;on-error&gt;
        &lt;base /&gt;
    &lt;/on-error&gt;
&lt;/policies&gt;

I also moved the policy to a separate file and deployed at apim operation level with the following bicep:

resource apiPolicy &#39;Microsoft.ApiManagement/service/apis/operations/policies@2022-09-01-preview&#39; = {
    name: &#39;${apimName}/amxapi_v1_0_0/entity/policy&#39;
    properties: {
        value: loadTextContent(&#39;./createEntityPolicy.xml&#39;)
    }
}

huangapple
  • 本文由 发表于 2023年5月6日 22:54:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76189545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定