Bylaw

Gallery › Managed Identity › Azure Community Policy

Assign Cross Subscription User-Assigned Managed Identity to Virtual Machine Scale Set

Converted Policy AuditIfNotExists DeployIfNotExists Disabled Mode Indexed Version 1.0.0

Assign User-Assigned Managed Identity that can be located in a different subscription to Virtual Machine Scale Set. Adapted from built-in /providers/Microsoft.Authorization/policyDefinitions/516187d4-ef64-4a1b-ad6b-a7348502976c. This policy is meant to be assigned at Management Group Level, otherwise you must assign manualy the permissions (Microsoft.Authorization/locks/write + Microsoft.Resources/deployments/* + */read) to the Policy Managed Idenity on the cross subscription UAMI.

ConvertTo-Bylaw converted this policy, and proved that the file compiles back to the same definition.

Azure Policy JSONazurepolicy.json · 407 lines
{
    "name": "7a38a53e-958c-50af-acca-fe2785e0cf7c",
    "type": "Microsoft.Authorization/policyDefinitions",
    "properties": {
      "displayName": "Assign Cross Subscription User-Assigned Managed Identity to Virtual Machine Scale Set",
      "mode": "Indexed",
      "description": "Assign User-Assigned Managed Identity that can be located in a different subscription to Virtual Machine Scale Set. Adapted from built-in /providers/Microsoft.Authorization/policyDefinitions/516187d4-ef64-4a1b-ad6b-a7348502976c. This policy is meant to be assigned at Management Group Level, otherwise you must assign manualy the permissions (Microsoft.Authorization/locks/write + Microsoft.Resources/deployments/* + */read) to the Policy Managed Idenity on the cross subscription UAMI.",
      "metadata": {
        "version": "1.0.0",
        "category": "Managed Identity"
      },
      "parameters": {
          "bringYourOwnUserAssignedManagedIdentity": {
              "type": "Boolean",
              "metadata": {
                  "displayName": "Bring Your Own User-Assigned Identity",
                  "description": "Enable this to use your pre-created user-assigned managed identity. The pre-created identity MUST exist within the subscription otherwise the policy deployment will fail. If enabled, ensure that the User-Assigned Identity Name and Identity Resource Group Name parameters match the pre-created identity. If not enabled, the policy will create per subscription, per resource user-assigned managed identities in a new resource group named 'Built-In-Identity-RG'."
              },
              "allowedValues": [
                  true,
                  false
              ]
          },
          "userAssignedIdentityName": {
              "type": "String",
              "metadata": {
                  "displayName": "User-Assigned Managed Identity Name",
                  "description": "The name of the pre-created user-assigned managed identity."
              },
              "defaultValue": ""
          },
          "identityResourceGroup": {
              "type": "String",
              "metadata": {
                  "displayName": "User-Assigned Managed Identity Resource Group Name",
                  "description": "The resource group in which the pre-created user-assigned managed identity resides."
              },
              "defaultValue": ""
          },
          "identitySubscription": {
              "type": "String",
              "metadata": {
                  "displayName": "User-Assigned Managed Identity Subscription ID",
                  "description": "The Subscription id of the pre-created user-assigned managed identity."
              },
              "defaultValue": ""
          },
          "builtInIdentityResourceGroupLocation": {
              "type": "String",
              "metadata": {
                  "displayName": "Built-In-Identity-RG Location",
                  "description": "The location of the resource group 'Built-In-Identity-RG' created by the policy. This parameter is only used when 'Bring Your Own User Assigned Identity' parameter is false."
              },
              "defaultValue": "eastus"
          },
          "effect": {
              "type": "String",
              "metadata": {
                  "displayName": "Effect",
                  "description": "The effect determines what happens when the policy rule is evaluated to match."
              },
              "allowedValues": [
                  "AuditIfNotExists",
                  "DeployIfNotExists",
                  "Disabled"
              ],
              "defaultValue": "DeployIfNotExists"
          }
      },
      "policyRule": {
          "if": {
              "allOf": [
                  {
                      "field": "type",
                      "equals": "Microsoft.Compute/virtualMachineScaleSets"
                  },
                  {
                      "value": "[requestContext().apiVersion]",
                      "greaterOrEquals": "2018-10-01"
                  }
              ]
          },
          "then": {
              "effect": "[parameters('effect')]",
              "details": {
                  "type": "Microsoft.Compute/virtualMachineScaleSets",
                  "name": "[field('name')]",
                  "evaluationDelay": "AfterProvisioning",
                  "deploymentScope": "subscription",
                  "existenceCondition": {
                      "anyOf": [
                          {
                              "allOf": [
                                  {
                                      "field": "identity.type",
                                      "contains": "UserAssigned"
                                  },
                                  {
                                      "field": "identity.userAssignedIdentities",
                                      "containsKey": "[if(parameters('bringYourOwnUserAssignedManagedIdentity'), concat('/subscriptions/', parameters('identitySubscription'), '/resourceGroups/', trim(parameters('identityResourceGroup')), '/providers/Microsoft.ManagedIdentity/userAssignedIdentities/', trim(parameters('userAssignedIdentityName'))), concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/Built-In-Identity-RG/providers/Microsoft.ManagedIdentity/userAssignedIdentities/Built-In-Identity-', field('location')))]"
                                  }
                              ]
                          },
                          {
                              "allOf": [
                                  {
                                      "field": "identity.type",
                                      "equals": "UserAssigned"
                                  },
                                  {
                                      "value": "[string(length(field('identity.userAssignedIdentities')))]",
                                      "equals": "1"
                                  }
                              ]
                          }
                      ]
                  },
                  "roleDefinitionIds": [
                      "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c",
                      "/providers/Microsoft.Authorization/roleDefinitions/18d7d88d-d35e-4fb5-a5c3-7773c20a72d9"
                  ],
                  "deployment": {
                      "location": "eastus",
                      "properties": {
                          "mode": "incremental",
                          "parameters": {
                              "bringYourOwnUserAssignedManagedIdentity": {
                                  "value": "[parameters('bringYourOwnUserAssignedManagedIdentity')]"
                              },
                              "location": {
                                  "value": "[field('location')]"
                              },
                              "uaName": {
                                  "value": "[if(parameters('bringYourOwnUserAssignedManagedIdentity'), parameters('userAssignedIdentityName'), 'Built-In-Identity')]"
                              },
                              "identityResourceGroup": {
                                  "value": "[if(parameters('bringYourOwnUserAssignedManagedIdentity'), parameters('identityResourceGroup'), 'Built-In-Identity-RG')]"
                              },
                              "identitySubscription": {
                                  "value": "[if(parameters('bringYourOwnUserAssignedManagedIdentity'), parameters('identitySubscription'), subscription().subscriptionId )]"
                              },
                              "builtInIdentityResourceGroupLocation": {
                                  "value": "[parameters('builtInIdentityResourceGroupLocation')]"
                              },
                              "vmName": {
                                  "value": "[field('name')]"
                              },
                              "vmResourceGroup": {
                                  "value": "[resourceGroup().name]"
                              },
                              "resourceId": {
                                  "value": "[field('id')]"
                              }
                          },
                          "template": {
                              "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
                              "contentVersion": "1.0.0.1",
                              "parameters": {
                                  "bringYourOwnUserAssignedManagedIdentity": {
                                      "type": "bool"
                                  },
                                  "location": {
                                      "type": "string"
                                  },
                                  "uaName": {
                                      "type": "string"
                                  },
                                  "identityResourceGroup": {
                                      "type": "string"
                                  },
                                  "identitySubscription": {
                                      "type": "string"
                                  },
                                  "builtInIdentityResourceGroupLocation": {
                                      "type": "string"
                                  },
                                  "vmName": {
                                      "type": "string"
                                  },
                                  "vmResourceGroup": {
                                      "type": "string"
                                  },
                                  "resourceId": {
                                      "type": "string"
                                  }
                              },
                              "variables": {
                                  "uaNameWithLocation": "[concat(parameters('uaName'),'-', parameters('location'))]",
                                  "precreatedUaId": "[concat('/subscriptions/', trim(parameters('identitySubscription')), '/resourceGroups/', trim(parameters('identityResourceGroup')), '/providers/Microsoft.ManagedIdentity/userAssignedIdentities/', trim(parameters('uaName')))]",
                                  "autocreatedUaId": "[concat('/subscriptions/', subscription().subscriptionId, '/resourceGroups/', trim(parameters('identityResourceGroup')), '/providers/Microsoft.ManagedIdentity/userAssignedIdentities/', trim(parameters('uaName')), '-', parameters('location'))]",
                                  "deployUALockName": "[concat('deployUALock-', uniqueString(deployment().name))]",
                                  "deployUAName": "[concat('deployUA-', uniqueString(deployment().name))]",
                                  "deployGetResourceProperties": "[concat('deployGetResourceProperties-', uniqueString(deployment().name))]",
                                  "deployAssignUAName": "[concat('deployAssignUA-', uniqueString(deployment().name))]"
                              },
                              "resources": [
                                  {
                                      "condition": "[not(parameters('bringYourOwnUserAssignedManagedIdentity'))]",
                                      "type": "Microsoft.Resources/resourceGroups",
                                      "apiVersion": "2020-06-01",
                                      "name": "[parameters('identityResourceGroup')]",
                                      "location": "[parameters('builtInIdentityResourceGroupLocation')]"
                                  },
                                  {
                                      "condition": "[parameters('bringYourOwnUserAssignedManagedIdentity')]",
                                      "type": "Microsoft.Resources/deployments",
                                      "apiVersion": "2020-06-01",
                                      "name": "[variables('deployUALockName')]",
                                      "resourceGroup": "[parameters('identityResourceGroup')]",
                                      "subscriptionId": "[parameters('identitySubscription')]",
                                      "properties": {
                                          "mode": "Incremental",
                                          "expressionEvaluationOptions": {
                                              "scope": "inner"
                                          },
                                          "parameters": {
                                              "uaName": {
                                                  "value": "[parameters('uaName')]"
                                              }
                                          },
                                          "template": {
                                              "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                                              "contentVersion": "1.0.0.0",
                                              "parameters": {
                                                  "uaName": {
                                                      "type": "string"
                                                  }
                                              },
                                              "variables": {},
                                              "resources": [
                                                  {
                                                      "type": "Microsoft.Authorization/locks",
                                                      "apiVersion": "2016-09-01",
                                                      "name": "[concat('CanNotDeleteLock-', parameters('uaName'))]",
                                                      "scope": "[concat('Microsoft.ManagedIdentity/userAssignedIdentities/', parameters('uaName'))]",
                                                      "properties": {
                                                          "level": "CanNotDelete",
                                                          "notes": "Please do not delete this User-Assigned Identity since extensions enabled by Azure Policy are relying on their existence."
                                                      }
                                                  }
                                              ]
                                          }
                                      }
                                  },
                                  {
                                      "condition": "[not(parameters('bringYourOwnUserAssignedManagedIdentity'))]",
                                      "type": "Microsoft.Resources/deployments",
                                      "apiVersion": "2020-06-01",
                                      "name": "[variables('deployUAName')]",
                                      "resourceGroup": "[parameters('identityResourceGroup')]",
                                      "dependsOn": [
                                          "[resourceId('Microsoft.Resources/resourceGroups', parameters('identityResourceGroup'))]"
                                      ],
                                      "properties": {
                                          "mode": "Incremental",
                                          "expressionEvaluationOptions": {
                                              "scope": "inner"
                                          },
                                          "parameters": {
                                              "uaName": {
                                                  "value": "[variables('uaNameWithLocation')]"
                                              },
                                              "location": {
                                                  "value": "[parameters('location')]"
                                              }
                                          },
                                          "template": {
                                              "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                                              "contentVersion": "1.0.0.0",
                                              "parameters": {
                                                  "uaName": {
                                                      "type": "string"
                                                  },
                                                  "location": {
                                                      "type": "string"
                                                  }
                                              },
                                              "variables": {},
                                              "resources": [
                                                  {
                                                      "type": "Microsoft.ManagedIdentity/userAssignedIdentities",
                                                      "name": "[parameters('uaName')]",
                                                      "apiVersion": "2018-11-30",
                                                      "location": "[parameters('location')]"
                                                  },
                                                  {
                                                      "type": "Microsoft.ManagedIdentity/userAssignedIdentities/providers/locks",
                                                      "apiVersion": "2016-09-01",
                                                      "name": "[concat(parameters('uaName'), '/Microsoft.Authorization/', 'CanNotDeleteLock-', parameters('uaName'))]",
                                                      "dependsOn": [
                                                          "[parameters('uaName')]"
                                                      ],
                                                      "properties": {
                                                          "level": "CanNotDelete",
                                                          "notes": "Please do not delete this User-Assigned Identity since extensions enabled by Azure Policy are relying on their existence."
                                                      }
                                                  }
                                              ]
                                          }
                                      }
                                  },
                                  {
                                      "type": "Microsoft.Resources/deployments",
                                      "apiVersion": "2020-06-01",
                                      "name": "[variables('deployGetResourceProperties')]",
                                      "location": "[parameters('location')]",
                                      "dependsOn": [
                                          "[resourceId('Microsoft.Resources/resourceGroups', parameters('identityResourceGroup'))]",
                                          "[variables('deployUAName')]"
                                      ],
                                      "properties": {
                                          "mode": "Incremental",
                                          "template": {
                                              "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                                              "contentVersion": "1.0.0.0",
                                              "resources": [],
                                              "outputs": {
                                                  "resource": {
                                                      "type": "object",
                                                      "value": "[reference(parameters('resourceId'), '2019-07-01', 'Full')]"
                                                  }
                                              }
                                          }
                                      }
                                  },
                                  {
                                      "type": "Microsoft.Resources/deployments",
                                      "apiVersion": "2020-06-01",
                                      "name": "[concat(variables('deployAssignUAName'))]",
                                      "resourceGroup": "[parameters('vmResourceGroup')]",
                                      "dependsOn": [
                                          "[resourceId('Microsoft.Resources/resourceGroups', parameters('identityResourceGroup'))]",
                                          "[variables('deployUAName')]",
                                          "[variables('deployGetResourceProperties')]"
                                      ],
                                      "properties": {
                                          "mode": "Incremental",
                                          "expressionEvaluationOptions": {
                                              "scope": "inner"
                                          },
                                          "parameters": {
                                              "uaId": {
                                                  "value": "[if(parameters('bringYourOwnUserAssignedManagedIdentity'), variables('precreatedUaId'), variables('autocreatedUaId'))]"
                                              },
                                              "vmName": {
                                                  "value": "[parameters('vmName')]"
                                              },
                                              "location": {
                                                  "value": "[parameters('location')]"
                                              },
                                              "identityType": {
                                                  "value": "[if(contains(reference(variables('deployGetResourceProperties')).outputs.resource.value, 'identity'), reference(variables('deployGetResourceProperties')).outputs.resource.value.identity.type, '')]"
                                              },
                                              "userAssignedIdentities": {
                                                  "value": "[if(and(contains(reference(variables('deployGetResourceProperties')).outputs.resource.value, 'identity'), contains(reference(variables('deployGetResourceProperties')).outputs.resource.value.identity, 'userAssignedIdentities')), reference(variables('deployGetResourceProperties')).outputs.resource.value.identity.userAssignedIdentities, createObject())]"
                                              }
                                          },
                                          "template": {
                                              "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                                              "contentVersion": "1.0.0.0",
                                              "parameters": {
                                                  "uaId": {
                                                      "type": "string"
                                                  },
                                                  "vmName": {
                                                      "type": "string"
                                                  },
                                                  "location": {
                                                      "type": "string"
                                                  },
                                                  "identityType": {
                                                      "type": "string"
                                                  },
                                                  "userAssignedIdentities": {
                                                      "type": "object"
                                                  }
                                              },
                                              "variables": {
                                                  "identityTypeValue": "[if(contains(parameters('identityType'), 'SystemAssigned'), 'SystemAssigned,UserAssigned', 'UserAssigned')]",
                                                  "userAssignedIdentitiesValue": "[union(parameters('userAssignedIdentities'), createObject(parameters('uaId'), createObject()))]",
                                                  "resourceWithSingleUAI": "[and(equals(parameters('identityType'), 'UserAssigned'), equals(string(length(parameters('userAssignedIdentities'))), '1'))]"
                                              },
                                              "resources": [
                                                  {
                                                      "condition": "[not(variables('resourceWithSingleUAI'))]",
                                                      "apiVersion": "2019-07-01",
                                                      "type": "Microsoft.Compute/virtualMachineScaleSets",
                                                      "name": "[parameters('vmName')]",
                                                      "location": "[parameters('location')]",
                                                      "identity": {
                                                          "type": "[variables('identityTypeValue')]",
                                                          "userAssignedIdentities": "[variables('userAssignedIdentitiesValue')]"
                                                      }
                                                  }
                                              ]
                                          }
                                      }
                                  }
                              ]
                          }
                      }
                  }
              }
          }
      }
    }
  }
Bylaw7a38a53e-958c-50af-acca-fe2785e0cf7c.bylaw.ps1 · 82 lines
# Converted from azurepolicy.json by ConvertTo-Bylaw.
Policy '7a38a53e-958c-50af-acca-fe2785e0cf7c' {

    Properties @{
        DisplayName = 'Assign Cross Subscription User-Assigned Managed Identity to Virtual Machine Scale Set'
        Description = 'Assign User-Assigned Managed Identity that can be located in a different subscription to Virtual Machine Scale Set. Adapted from built-in /providers/Microsoft.Authorization/policyDefinitions/516187d4-ef64-4a1b-ad6b-a7348502976c. This policy is meant to be assigned at Management Group Level, otherwise you must assign manualy the permissions (Microsoft.Authorization/locks/write + Microsoft.Resources/deployments/* + */read) to the Policy Managed Idenity on the cross subscription UAMI.'
        Version     = '1.0.0'
        Category    = 'Managed Identity'
        Mode        = 'Indexed'
    }

    Parameter BringYourOwnUserAssignedManagedIdentity @{
        Type          = 'Boolean'
        AllowedValues = @($true, $false)
        DisplayName   = 'Bring Your Own User-Assigned Identity'
        Description   = 'Enable this to use your pre-created user-assigned managed identity. The pre-created identity MUST exist within the subscription otherwise the policy deployment will fail. If enabled, ensure that the User-Assigned Identity Name and Identity Resource Group Name parameters match the pre-created identity. If not enabled, the policy will create per subscription, per resource user-assigned managed identities in a new resource group named ''Built-In-Identity-RG''.'
    }
    Parameter UserAssignedIdentityName @{
        Default     = ''
        DisplayName = 'User-Assigned Managed Identity Name'
        Description = 'The name of the pre-created user-assigned managed identity.'
    }
    Parameter IdentityResourceGroup @{
        Default     = ''
        DisplayName = 'User-Assigned Managed Identity Resource Group Name'
        Description = 'The resource group in which the pre-created user-assigned managed identity resides.'
    }
    Parameter IdentitySubscription @{
        Default     = ''
        DisplayName = 'User-Assigned Managed Identity Subscription ID'
        Description = 'The Subscription id of the pre-created user-assigned managed identity.'
    }
    Parameter BuiltInIdentityResourceGroupLocation @{
        Default     = 'eastus'
        DisplayName = 'Built-In-Identity-RG Location'
        Description = 'The location of the resource group ''Built-In-Identity-RG'' created by the policy. This parameter is only used when ''Bring Your Own User Assigned Identity'' parameter is false.'
    }
    Parameter Effect @{
        AllowedValues = @('AuditIfNotExists', 'DeployIfNotExists', 'Disabled')
        Default       = 'DeployIfNotExists'
        DisplayName   = 'Effect'
        Description   = 'The effect determines what happens when the policy rule is evaluated to match.'
    }

    Resource 'Microsoft.Compute/virtualMachineScaleSets' {

        Require 'Requirement 1' {
            Arm '[requestContext().apiVersion]' | Must -BeLessThan '2018-10-01'
        }
    }

    DeployIfNotExists 'Microsoft.Compute/virtualMachineScaleSets' -Role 'Contributor', 'User Access Administrator' -Name (Arm '[field(''name'')]') -EvaluationDelay AfterProvisioning -Effect (Param Effect) {
        Require 'identity.type, identity.userAssignedIdentities and location are as required' {
            AnyOf {
                AllOf {
                    Field identity.type | Must -ContainText 'UserAssigned'
                    Field identity.userAssignedIdentities | Must -ContainKey (Arm '[if(parameters(''bringYourOwnUserAssignedManagedIdentity''), concat(''/subscriptions/'', parameters(''identitySubscription''), ''/resourceGroups/'', trim(parameters(''identityResourceGroup'')), ''/providers/Microsoft.ManagedIdentity/userAssignedIdentities/'', trim(parameters(''userAssignedIdentityName''))), concat(''/subscriptions/'', subscription().subscriptionId, ''/resourceGroups/Built-In-Identity-RG/providers/Microsoft.ManagedIdentity/userAssignedIdentities/Built-In-Identity-'', field(''location'')))]')
                }
                AllOf {
                    Field identity.type | Must -Be 'UserAssigned'
                    Arm '[string(length(field(''identity.userAssignedIdentities'')))]' | Must -Be '1'
                }
            }
        }
        Deployment @{
            TemplateFile = './templates/7a38a53e-958c-50af-acca-fe2785e0cf7c.json'
            Scope        = 'Subscription'
            Location     = 'eastus'
            Parameters   = [ordered]@{
                bringYourOwnUserAssignedManagedIdentity = (Param BringYourOwnUserAssignedManagedIdentity)
                location                                = (Arm '[field(''location'')]')
                uaName                                  = (Arm '[if(parameters(''bringYourOwnUserAssignedManagedIdentity''), parameters(''userAssignedIdentityName''), ''Built-In-Identity'')]')
                identityResourceGroup                   = (Arm '[if(parameters(''bringYourOwnUserAssignedManagedIdentity''), parameters(''identityResourceGroup''), ''Built-In-Identity-RG'')]')
                identitySubscription                    = (Arm '[if(parameters(''bringYourOwnUserAssignedManagedIdentity''), parameters(''identitySubscription''), subscription().subscriptionId )]')
                builtInIdentityResourceGroupLocation    = (Param BuiltInIdentityResourceGroupLocation)
                vmName                                  = (Arm '[field(''name'')]')
                vmResourceGroup                         = (Arm '[resourceGroup().name]')
                resourceId                              = (Arm '[field(''id'')]')
            }
        }
    }
}

Its deployment templates are written beside it:

Source: policyDefinitions/Managed Identity/assign-cross-subscription-user-assigned-managed-identity-to-virtual-machine-scale-set/azurepolicy.json in Azure/Community-Policy, under the MIT licence.