Looping through values in ARM templates

2019-08-17 14:32发布

问题:

I've been working on an issue I'm having with ARM templates for over a day now, and seem to be stuck, so asking on SO in case anyone can help.

To describe the issue, I've got an existing Azure Key Vault setup, and wish to add a number of access policies to this resource group. For reference purposes, the following is the ARM template reference for adding Key Vault Access Policies:

https://docs.microsoft.com/en-gb/azure/templates/Microsoft.KeyVault/2018-02-14/vaults/accessPolicies

I have a number of users I wish to assign the same permissions to, and this list of users is unlikely to change frequently, so I wish to hardcode an array of objectIds referring to these users within the template itself, and then use the "copy" functionality to create multiple access policy . Essentially I want the end result to be close to this, where the only value that changes between access policies is the objectID identifying the user:

{
    "name": "TestKeyVault/add",
    "type": "Microsoft.KeyVault/vaults/accessPolicies",
    "apiVersion": "2018-02-14",
    "properties": {
        "accessPolicies": [

            {
                "tenantId": "tenantIDStringGoesHere",
                "objectId": "guidForUser1GoesHere",
                "permissions": {
                    "keys": ["List"],
                    "secrets": ["List"],
                    "certificates": ["List"]
                }
            },

            {
                "tenantId": "tenantIDStringGoesHere",
                "objectId": "guidForUser2GoesHere",
                "permissions": {
                    "keys": ["List"],
                    "secrets": ["List"],
                    "certificates": ["List"]
                }
            }

        ]   
    }
}

The reason I want to sort this out with a loop rather than duplicating the access policies by hand is that I believe it'll make maintenance easier, as personnel changes can be handled by adding or removing values from an array rather than having to duplicate or remove larger portions of text.

I've tried to understand the "copy" syntax outlined here, but I haven't found the right combination that works for my use case:

https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-multiple

The closest I've got is the following:

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {

    "keyVaultName": {
      "type": "string",
      "metadata": {
        "description": "Name of the Vault"
      }
    },

    "tenantId": {
      "type": "string",
      "defaultValue": "[subscription().tenantId]",
      "metadata": {
        "description": "Tenant Id of the subscription. Get using Get-AzureRmSubscription cmdlet or Get Subscription API"
      }
    },

    "objectId": {
      "type": "array",
      "defaultValue": [
        "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"
      ],
      "metadata": {
        "description": "Object Id of the AD user. Get using Get-AzureRmADUser or Get-AzureRmADServicePrincipal cmdlets"
      }
    },

    "secretsPermissions": {
      "type": "array",
      "defaultValue": [
        "list"
      ],
      "metadata": {
        "description": "Permissions to secrets in the vault. Valid values are: all, get, set, list, and delete."
      }
    }

  },

  "variables": {
    "objectIdCount": "[length(parameters('objectId'))]"
  },

  "resources": [
    {

      "type": "Microsoft.KeyVault/vaults/accessPolicies",
      "name": "TestKeyVault/add",
      "apiVersion": "2018-02-14",
      "properties": {
        "accessPolicies": [{
          "tenantId": "[parameters('tenantId')]",
          "objectId": "[parameters('objectId')[copyIndex('objectIdCopy')]]",
          "permissions": {
            "secrets": "[parameters('secretsPermissions')]"
          },
          "copy": {
            "name": "objectIdCopy",
            "count": 2
          }


        }]
      }

    }
  ]

}

Worth noting that whilst I've replaced the objectIds in this SO version with X's and Y's, the code works in the real version if I replace "objectId": "[parameters('objectId')[copyIndex('objectIdCopy')]]" with "objectId": "[parameters('objectId')[0]]" (in other words, if I just hardcode the array index it works, but if I try to use copyIndex it does not).

I've had various error messages with the different variants of this template that I've tried, but with this latest iteration the error message I get when attempting to deploy the template through PowerShell can basically be summarised as "The template function 'copyIndex' is not expected at this location".

Talking of the PowerShell I've been using to test it, the following is a simplified version:

Clear-Host

$deploymentResourceGroupName = 'TestRG'

$templatePath = 'test_template.json'

$templateParameterObject = @{}
$templateParameterObject += @{'keyVaultName' = 'TestKeyVault'}

New-AzureRmResourceGroupDeployment -ResourceGroupName $deploymentResourceGroupName -TemplateFile $templatePath -TemplateParameterObject $templateParameterObject

I realise this is a long question, but I'm hoping I've provided sufficient information to help with debugging this.

Any suggestions what I should change to get the copy functionality working?

回答1:

This is more or less what you want (if I understand you properly):

{
    "type": "Microsoft.KeyVault/vaults/accessPolicies",
    "name": "TestKeyVault/add",
    "apiVersion": "2018-02-14",
    "properties": {
        "copy": [
            {
                "name": "accessPolicies",
                "count": "[length(parameters('objectId'))]",
                "input": {
                    "tenantId": "[parameters('tenantId')]",
                    "objectId": "[parameters('objectId')[copyIndex('accessPolicies')]]",
                    "permissions": {
                        "secrets": "[parameters('secretsPermissions')]"
                    }
                }
            }
        ]
    }
}

Reading: https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-multiple#property-iteration