首页 > 解决方案 > 获取 ARM 模板中的对象属性名称数组

问题描述

在 ARM 模板中,有没有办法获取包含 JSON 对象属性名称的数组?我在文档中看不到任何明显的东西。我看到的最接近的是length(object)获取对象的属性计数,但我认为我什至不能使用复制循环来获取属性名称。

我要实现的特定场景是将appsettings具有附加插槽粘性设置的 Web 部署到暂存插槽:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "webSiteName": {
      "type": "string"
    },
    "globalAppSettings": {
      "type": "object"
    },
    "slotName": {
      "type": "string"
    },
    "slotAppSettings": {
      "type": "object"
    },
    "slotStickySettings": {
      "type": "array",
      // but getPropertyNames(object) is not a real function :(
      "defaultValue": "[getPropertyNames(parameters('slotAppSettings'))]"
    }
  },
  "resources": [
    {
      "type": "Microsoft.Web/sites/config",
      "name": "[concat(parameters('webSiteName'), '/appsettings')]",
      "apiVersion": "2018-02-01",
      "properties": "[parameters('globalAppSettings')]"
    },
    {
      "type": "Microsoft.Web/sites/slots/config",
      "name": "[concat(parameters('webSiteName'), '/', parameters('slotName'), '/appsettings')]",
      "apiVersion": "2018-02-01",
      "properties": "[union(parameters('globalAppSettings'), parameters('slotAppSettings'))]"
    },
    {
      "type": "Microsoft.Web/sites/config",
      "name": "[concat(parameters('webSiteName'), '/slotconfignames')]",
      "apiVersion": "2015-08-01",
      "properties": {
        "appSettingNames": "[parameters('slotStickySettings')]"
      }
    }
  ]
}

标签: jsonazure-web-app-servicearm-templateazure-deployment-slots

解决方案


没有一种直接的方法可以做到这一点,因为没有函数可以返回对象的属性。我能够通过将对象转换为字符串然后解析它以找到属性名称来完成它。只要您的属性值中没有逗号,它就应该起作用。如果需要,您可能还可以添加一些检查来处理这种情况。

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "testSettings": {
            "type": "object",
            "defaultValue": {
                "a": "demo value 1",
                "b": "demo value 2"
            }
        }
    },
    "variables": {
        "delimiters": [","],
        "settingArray": "[split(replace(replace(replace(string(parameters('testSettings')), '{', ''), '}', ''), '\"', ''), variables('delimiters'))]",
        "propNameArray": {
            "copy": [
                {
                    "name": "copyPropertyNames",
                    "count": "[length(variables('settingArray'))]",
                    "input": "[substring(variables('settingArray')[copyIndex('copyPropertyNames')], 0, indexOf(variables('settingArray')[copyIndex('copyPropertyNames')], ':'))]"
                }
            ]
        }
    },
    "resources": [],
    "outputs": {
        "paramOutput": {
            "type": "array",
            "value": "[variables('propNameArray').copyPropertyNames]"
        }
    }
}

推荐阅读