如何转义ARM模板中的单引号

How to escape single quote in ARM template

给定 AzureRM 模板中的以下资源,如何对 commandToExecute 部分中的单引号进行编码?

{
  "type": "Microsoft.Compute/virtualMachines/extensions",
  "name": "[concat(variables('vmNameMaster'), copyIndex(), '/sethost')]",
  "apiVersion": "2015-06-15",
  "location": "[resourceGroup().location]",
  "copy": {
      "name": "extensionLoopNode",
      "count": "[variables('masterCount')]"
  },
  "dependsOn": [
      "[concat('Microsoft.Compute/virtualMachines/', variables('vmNameMaster'), copyIndex(),'/extensions/DockerExtension')]"
  ],
  "properties": {
    "publisher": "Microsoft.OSTCExtensions",
    "type": "CustomScriptForLinux",
    "typeHandlerVersion": "1.4",
    "settings": {
      "fileUris": [ ],
      "commandToExecute": "[concat('/bin/bash -c \'echo \"export DOCKER_HOST=:2375\" >> /home/', parameters('adminUsername') ,'/.profile\'')]",
      "timestamp": 123456789
    }
  }
},

不必在 commandToExecute 部分对单引号进行编码。 下面的 json 段已在 json 中验证为有效 http://jsonlint.com/

{
    "type": "Microsoft.Compute / virtualMachines / extensions ",
    "name": "[concat(variables('vmNameMaster'), copyIndex(), '/sethost')]",
    "apiVersion": "2015-06-15",
    "location": "[resourceGroup().location]",
    "copy": {
        "name": "extensionLoopNode",
        "count": "[variables('masterCount')]"
    },
    "dependsOn": [
        "[concat('Microsoft.Compute/virtualMachines/', variables('vmNameMaster'), copyIndex(),'/extensions/DockerExtension')]"
    ],
    "properties": {
        "publisher": "Microsoft.OSTCExtensions",
        "type": "CustomScriptForLinux",
        "typeHandlerVersion": "1.4",
        "settings": {
            "fileUris": [],
            "commandToExecute": "[concat('/bin/bash -c 'echo \"export DOCKER_HOST=:2375\" >> /home/', parameters('adminUsername') ,'/.profile'')]",
            "timestamp": 123456789
        }
    }
}

我用一个变量解决了这个问题:

"variables": {
    "singleQuote": "'",
},
...
"settings": {
    "fileUris": [],
    "commandToExecute": "[concat('/bin/bash -c ', variables('singleQuote'), 'echo \"export DOCKER_HOST=:2375\" >> /home/', parameters('adminUsername') ,'/.profile', variables('singleQuote'))]",
}

虽然不优雅,但很管用。

您可以使用与 VB 字符串相同的方式转义 Azure ARM 函数:只需将单引号字符加倍即可。

[concat('This is a ''quoted'' word.')]

产出

This is a 'quoted' word.

JSON.

双引号还需要转义
 [concat('''single'' and \"double\" quotes.')]

产出

'single' and "double" quotes.

在 DevOps 发布管道中,对于 APIM 策略,使用 & quote;转义表达式中的引号,

<when condition='@(context.Variables.GetValueOrDefault&lt;bool&gt;(&quot;isAuthOk&quot;))' />