在订阅级别创建资源组和资源Create resource groups and resources at the subscription level

若要简化资源管理,可以使用 Azure 资源管理器模板(ARM 模板)在 Azure 订阅级别部署资源。To simplify the management of resources, you can use an Azure Resource Manager template (ARM template) to deploy resources at the level of your Azure subscription. 例如,可以将策略Azure 基于角色的访问控制 (Azure RBAC) 部署到你的订阅中,从而将它们应用于整个订阅。For example, you can deploy policies and Azure role-based access control (Azure RBAC) to your subscription, which applies them across your subscription. 还可以在订阅中创建资源组,然后将资源部署到订阅中的资源组。You can also create resource groups within the subscription and deploy resources to resource groups in the subscription.

备注

可在订阅级别部署中部署到 800 个不同的资源组。You can deploy to 800 different resource groups in a subscription level deployment.

若要在订阅级别部署模板,请使用 Azure CLI、PowerShell、REST API 或门户。To deploy templates at the subscription level, use Azure CLI, PowerShell, REST API, or the portal.

支持的资源Supported resources

并非所有资源类型都可以部署到订阅级别。Not all resource types can be deployed to the subscription level. 本部分列出了支持的资源类型。This section lists which resource types are supported.

对于 Azure 蓝图,请使用:For Azure Blueprints, use:

  • 项目artifacts
  • blueprintsblueprints
  • blueprintAssignmentsblueprintAssignments
  • versionsversions

对于 Azure 策略:For Azure Policies:

  • policyAssignmentspolicyAssignments
  • policyDefinitionspolicyDefinitions
  • policySetDefinitionspolicySetDefinitions
  • remediationsremediations

对于基于角色的访问控制,请使用:For role-based access control, use:

  • roleAssignmentsroleAssignments
  • roleDefinitionsroleDefinitions

对于部署到资源组的嵌套模板,请使用:For nested templates that deploy to resource groups, use:

  • deploymentsdeployments

若要创建新的资源组,请使用:For creating new resource groups, use:

  • resourceGroupsresourceGroups

若要管理订阅,请使用:For managing your subscription:

  • 预算budgets
  • supportPlanTypessupportPlanTypes
  • 标记tags

其他支持的类型包括:Other supported types include:

  • scopeAssignmentsscopeAssignments
  • eventSubscriptionseventSubscriptions
  • peerAsnspeerAsns

架构Schema

用于订阅级别部署的架构不同于资源组部署的架构。The schema you use for subscription-level deployments is different than the schema for resource group deployments.

对于模板,请使用:For templates, use:

https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#

对于所有部署范围,参数文件的架构都相同。The schema for a parameter file is the same for all deployment scopes. 对于参数文件,请使用:For parameter files, use:

https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#

部署命令Deployment commands

用于订阅级别部署的命令与资源组部署使用的命令不同。The commands for subscription-level deployments are different than the commands for resource group deployments.

对于 Azure CLI,请使用 az deployment sub createFor Azure CLI, use az deployment sub create. 以下示例会部署一个模板来创建资源组:The following example deploys a template to create a resource group:

az deployment sub create \
  --name demoSubDeployment \
  --location chinaeast \
  --template-uri "https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/emptyRG.json" \
  --parameters rgName=demoResourceGroup rgLocation=chinaeast

对于 PowerShell 部署命令,请使用 New-AzDeploymentNew-AzSubscriptionDeploymentFor the PowerShell deployment command, use New-AzDeployment or New-AzSubscriptionDeployment. 以下示例会部署一个模板来创建资源组:The following example deploys a template to create a resource group:

New-AzSubscriptionDeployment `
  -Name demoSubDeployment `
  -Location chinaeast `
  -TemplateUri "https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/emptyRG.json" `
  -rgName demoResourceGroup `
  -rgLocation chinaeast

对于 REST API,请使用部署 - 在订阅范围内创建For REST API, use Deployments - Create At Subscription Scope.

部署位置和名称Deployment location and name

对于订阅级别部署,必须为部署提供位置。For subscription level deployments, you must provide a location for the deployment. 部署位置独立于部署的资源的位置。The location of the deployment is separate from the location of the resources you deploy. 部署位置指定何处存储部署数据。The deployment location specifies where to store deployment data.

可以为部署提供一个名称,也可以使用默认部署名称。You can provide a name for the deployment, or use the default deployment name. 默认名称是模板文件的名称。The default name is the name of the template file. 例如,部署一个名为 azuredeploy.json 的模板将创建默认部署名称 azuredeployFor example, deploying a template named azuredeploy.json creates a default deployment name of azuredeploy.

每个部署名称的位置不可变。For each deployment name, the location is immutable. 当某个位置中已有某个部署时,无法在另一位置创建同名的部署。You can't create a deployment in one location when there's an existing deployment with the same name in a different location. 如果出现错误代码 InvalidDeploymentLocation,请使用其他名称或使用与该名称的以前部署相同的位置。If you get the error code InvalidDeploymentLocation, either use a different name or the same location as the previous deployment for that name.

部署范围Deployment scopes

部署到订阅时,可以将订阅或订阅中的任何资源组作为目标。When deploying to a subscription, you can target the subscription or any resource groups within the subscription. 部署模板的用户必须有权访问指定的作用域。The user deploying the template must have access to the specified scope.

将对订阅应用模板的资源部分中定义的资源。Resources defined within the resources section of the template are applied to the subscription.

{
    "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "resources": [
        subscription-level-resources
    ],
    "outputs": {}
}

若要以订阅中的资源组为目标,请添加嵌套部署并包括 resourceGroup 属性。To target a resource group within the subscription, add a nested deployment and include the resourceGroup property. 在以下示例中,嵌套部署以名为 rg2 的资源组为目标。In the following example, the nested deployment targets a resource group named rg2.

{
    "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "resources": [
        {
            "type": "Microsoft.Resources/deployments",
            "apiVersion": "2020-06-01",
            "name": "nestedDeployment",
            "resourceGroup": "rg2",
            "properties": {
                "mode": "Incremental",
                "template": {
                    nested-template
                }
            }
        }
    ],
    "outputs": {}
}

使用模板函数Use template functions

对于订阅级别部署,在使用模板函数时有一些重要注意事项:For subscription-level deployments, there are some important considerations when using template functions:

  • 不支持 resourceGroup() 函数。The resourceGroup() function is not supported.

  • 支持 reference()list() 函数。The reference() and list() functions are supported.

  • 使用 subscriptionResourceId() 函数获取在订阅级别部署的资源的资源 ID。Use the subscriptionResourceId() function to get the resource ID for resources that are deployed at subscription level.

    例如,若要获取策略定义的资源 ID,请使用:For example, to get the resource ID for a policy definition, use:

    subscriptionResourceId('Microsoft.Authorization/roleDefinitions/', parameters('roleDefinition'))
    

    返回的资源 ID 具有以下格式:The returned resource ID has the following format:

    /subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
    

资源组Resource groups

创建资源组Create resource groups

若要在 ARM 模板中创建资源组,请为该资源组定义包含名称和位置的 Microsoft.Resources/resourceGroups 资源。To create a resource group in an ARM template, define a Microsoft.Resources/resourceGroups resource with a name and location for the resource group.

以下模板创建空资源组。The following template creates an empty resource group.

{
  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "rgName": {
      "type": "string"
    },
    "rgLocation": {
      "type": "string"
    }
  },
  "variables": {},
  "resources": [
    {
      "type": "Microsoft.Resources/resourceGroups",
      "apiVersion": "2020-06-01",
      "name": "[parameters('rgName')]",
      "location": "[parameters('rgLocation')]",
      "properties": {}
    }
  ],
  "outputs": {}
}

结合使用 copy 元素与资源组来创建多个资源组。Use the copy element with resource groups to create more than one resource group.

{
  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "rgNamePrefix": {
      "type": "string"
    },
    "rgLocation": {
      "type": "string"
    },
    "instanceCount": {
      "type": "int"
    }
  },
  "variables": {},
  "resources": [
    {
      "type": "Microsoft.Resources/resourceGroups",
      "apiVersion": "2020-06-01",
      "location": "[parameters('rgLocation')]",
      "name": "[concat(parameters('rgNamePrefix'), copyIndex())]",
      "copy": {
        "name": "rgCopy",
        "count": "[parameters('instanceCount')]"
      },
      "properties": {}
    }
  ],
  "outputs": {}
}

有关资源迭代的信息,请参阅在 Azure 资源管理器模板中部署资源的多个实例,以及教程:使用资源管理器模板创建多个资源实例For information about resource iteration, see Deploy more than one instance of a resource in Azure Resource Manager Templates, and Tutorial: Create multiple resource instances with Resource Manager templates.

创建资源组和资源Create resource group and resources

若要创建资源组并向其部署资源,请使用嵌套模板。To create the resource group and deploy resources to it, use a nested template. 嵌套模板定义要部署到资源组的资源。The nested template defines the resources to deploy to the resource group. 将嵌套模板设置为依赖于资源组,确保资源组存在,然后再部署资源。Set the nested template as dependent on the resource group to make sure the resource group exists before deploying the resources. 最多可部署到 800 个资源组。You can deploy to up to 800 resource groups.

以下示例将创建一个资源组,并向该资源组部署存储帐户。The following example creates a resource group, and deploys a storage account to the resource group.

{
  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "rgName": {
      "type": "string"
    },
    "rgLocation": {
      "type": "string"
    },
    "storagePrefix": {
      "type": "string",
      "maxLength": 11
    }
  },
  "variables": {
    "storageName": "[concat(parameters('storagePrefix'), uniqueString(subscription().id, parameters('rgName')))]"
  },
  "resources": [
    {
      "type": "Microsoft.Resources/resourceGroups",
      "apiVersion": "2020-06-01",
      "name": "[parameters('rgName')]",
      "location": "[parameters('rgLocation')]",
      "properties": {}
    },
    {
      "type": "Microsoft.Resources/deployments",
      "apiVersion": "2020-06-01",
      "name": "storageDeployment",
      "resourceGroup": "[parameters('rgName')]",
      "dependsOn": [
        "[resourceId('Microsoft.Resources/resourceGroups/', parameters('rgName'))]"
      ],
      "properties": {
        "mode": "Incremental",
        "template": {
          "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
          "contentVersion": "1.0.0.0",
          "parameters": {},
          "variables": {},
          "resources": [
            {
              "type": "Microsoft.Storage/storageAccounts",
              "apiVersion": "2019-06-01",
              "name": "[variables('storageName')]",
              "location": "[parameters('rgLocation')]",
              "sku": {
                "name": "Standard_LRS"
              },
              "kind": "StorageV2"
            }
          ],
          "outputs": {}
        }
      }
    }
  ],
  "outputs": {}
}

Azure PolicyAzure Policy

分配策略定义Assign policy definition

以下示例将现有的策略定义分配到订阅。The following example assigns an existing policy definition to the subscription. 如果策略定义使用参数,请将参数作为对象提供。If the policy definition takes parameters, provide them as an object. 如果策略定义不使用参数,请使用默认的空对象。If the policy definition doesn't take parameters, use the default empty object.

{
  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "policyDefinitionID": {
      "type": "string"
    },
    "policyName": {
      "type": "string"
    },
    "policyParameters": {
      "type": "object",
      "defaultValue": {}
    }
  },
  "variables": {},
  "resources": [
    {
      "type": "Microsoft.Authorization/policyAssignments",
      "apiVersion": "2018-03-01",
      "name": "[parameters('policyName')]",
      "properties": {
        "scope": "[subscription().id]",
        "policyDefinitionId": "[parameters('policyDefinitionID')]",
        "parameters": "[parameters('policyParameters')]"
      }
    }
  ]
}

若要使用 Azure CLI 部署此模板,请使用:To deploy this template with Azure CLI, use:

# Built-in policy definition that accepts parameters
definition=$(az policy definition list --query "[?displayName=='Allowed locations'].id" --output tsv)

az deployment sub create \
  --name demoDeployment \
  --location chinaeast \
  --template-uri "https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/policyassign.json" \
  --parameters policyDefinitionID=$definition policyName=setLocation policyParameters="{'listOfAllowedLocations': {'value': ['chinanorth']} }"

若要使用 PowerShell 部署此模板,请使用:To deploy this template with PowerShell, use:

$definition = Get-AzPolicyDefinition | Where-Object { $_.Properties.DisplayName -eq 'Allowed locations' }

$locations = @("chinanorth", "chinanorth2")
$policyParams =@{listOfAllowedLocations = @{ value = $locations}}

New-AzSubscriptionDeployment `
  -Name policyassign `
  -Location chinaeast `
  -TemplateUri "https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/policyassign.json" `
  -policyDefinitionID $definition.PolicyDefinitionId `
  -policyName setLocation `
  -policyParameters $policyParams

创建和分配策略定义Create and assign policy definitions

可在同一模板中定义和分配策略定义。You can define and assign a policy definition in the same template.

{
  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {},
  "variables": {},
  "resources": [
    {
      "type": "Microsoft.Authorization/policyDefinitions",
      "apiVersion": "2018-05-01",
      "name": "locationpolicy",
      "properties": {
        "policyType": "Custom",
        "parameters": {},
        "policyRule": {
          "if": {
            "field": "location",
            "equals": "chinaeast2"
          },
          "then": {
            "effect": "deny"
          }
        }
      }
    },
    {
      "type": "Microsoft.Authorization/policyAssignments",
      "apiVersion": "2018-05-01",
      "name": "location-lock",
      "dependsOn": [
        "locationpolicy"
      ],
      "properties": {
        "scope": "[subscription().id]",
        "policyDefinitionId": "[resourceId('Microsoft.Authorization/policyDefinitions', 'locationpolicy')]"
      }
    }
  ]
}

若要在订阅中创建策略定义,然后将其分配到订阅,请使用以下 CLI 命令:To create the policy definition in your subscription, and assign it to the subscription, use the following CLI command:

az deployment sub create \
  --name demoDeployment \
  --location chinaeast \
  --template-uri "https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/policydefineandassign.json"

若要使用 PowerShell 部署此模板,请使用:To deploy this template with PowerShell, use:

New-AzSubscriptionDeployment `
  -Name definePolicy `
  -Location chinaeast `
  -TemplateUri "https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/policydefineandassign.json"

Azure 蓝图Azure Blueprints

创建蓝图定义Create blueprint definition

可通过模板创建蓝图定义。You can create a blueprint definition from a template.

{
  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "blueprintName": {
      "defaultValue": "sample-blueprint",
      "type": "String",
      "metadata": {
        "description": "The name of the blueprint definition."
      }
    }
  },
  "resources": [
    {
      "type": "Microsoft.Blueprint/blueprints",
      "apiVersion": "2018-11-01-preview",
      "name": "[parameters('blueprintName')]",
      "properties": {
        "targetScope": "subscription",
        "description": "Blueprint with a policy assignment artifact.",
        "resourceGroups": {
          "sampleRg": {
            "description": "Resource group to add the assignment to."
          }
        },
        "parameters": {
          "listOfResourceTypesNotAllowed": {
            "type": "array",
            "metadata": {
              "displayName": "Resource types to pass to the policy assignment artifact."
            },
            "defaultValue": [
              "Citrix.Cloud/accounts"
            ]
          }
        }
      }
    },
    {
      "type": "Microsoft.Blueprint/blueprints/artifacts",
      "apiVersion": "2018-11-01-preview",
      "name": "[concat(parameters('blueprintName'), '/policyArtifact')]",
      "kind": "policyAssignment",
      "dependsOn": [
        "[parameters('blueprintName')]"
      ],
      "properties": {
        "displayName": "Blocked Resource Types policy definition",
        "description": "Block certain resource types",
        "policyDefinitionId": "[tenantResourceId('Microsoft.Authorization/policyDefinitions', '6c112d4e-5bc7-47ae-a041-ea2d9dccd749')]",
        "resourceGroup": "sampleRg",
        "parameters": {
          "listOfResourceTypesNotAllowed": {
            "value": "[[parameters('listOfResourceTypesNotAllowed')]"
          }
        }
      }
    }
  ]
}

若要在订阅中创建蓝图定义,请使用以下 CLI 命令:To create the blueprint definition in your subscription, use the following CLI command:

az deployment sub create \
  --name demoDeployment \
  --location chinaeast \
  --template-uri "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/subscription-deployments/blueprints-new-blueprint/azuredeploy.json"

若要使用 PowerShell 部署此模板,请使用:To deploy this template with PowerShell, use:

New-AzSubscriptionDeployment `
  -Name demoDeployment `
  -Location chinaeast `
  -TemplateUri "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/subscription-deployments/blueprints-new-blueprint/azuredeploy.json"

访问控制Access control

若要了解如何分配角色,请参阅使用 Azure 资源管理器模板添加 Azure 角色分配To learn about assigning roles, see Add Azure role assignments using Azure Resource Manager templates.

以下示例创建一个资源组,对其应用锁定,并为主体分配一个角色。The following example creates a resource group, applies a lock to it, and assigns a role to a principal.

{
  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "rgName": {
      "type": "string",
      "metadata": {
        "description": "Name of the resourceGroup to create"
      }
    },
    "rgLocation": {
      "type": "string",
      "metadata": {
        "description": "Location for the resourceGroup"
      }
    },
    "principalId": {
      "type": "string",
      "metadata": {
        "description": "principalId if the user that will be given contributor access to the resourceGroup"
      }
    },
    "roleDefinitionId": {
      "type": "string",
      "defaultValue": "b24988ac-6180-42a0-ab88-20f7382dd24c",
      "metadata": {
        "description": "roleDefinition to apply to the resourceGroup - default is contributor"
      }
    },
    "roleAssignmentName": {
      "type": "string",
      "defaultValue": "[guid(parameters('principalId'), parameters('roleDefinitionId'), parameters('rgName'))]",
      "metadata": {
        "description": "Unique name for the roleAssignment in the format of a guid"
      }
    }
  },
  "variables": { },
  "resources": [
    {
      "type": "Microsoft.Resources/resourceGroups",
      "apiVersion": "2019-10-01",
      "name": "[parameters('rgName')]",
      "location": "[parameters('rgLocation')]",
      "tags": {
        "Note": "subscription level deployment"
      },
      "properties": {}
    },
    {
      "type": "Microsoft.Resources/deployments",
      "apiVersion": "2019-10-01",
      "name": "applyLock",
      "resourceGroup": "[parameters('rgName')]",
      "dependsOn": [
        "[parameters('rgName')]"
      ],
      "properties": {
        "mode": "Incremental",
        "template": {
          "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
          "contentVersion": "1.0.0.0",
          "resources": [
            {
              "type": "Microsoft.Authorization/locks",
              "apiVersion": "2017-04-01",
              "name": "DontDelete",
              "properties": {
                "level": "CanNotDelete",
                "notes": "Prevent deletion of the resourceGroup"
              }
            },
            {
              "type": "Microsoft.Authorization/roleAssignments",
              "apiVersion": "2020-03-01-preview",
              "name": "[guid(parameters('roleAssignmentName'))]",
              "properties": {
                "roleDefinitionId": "[subscriptionResourceId('Microsoft.Authorization/roleDefinitions', parameters('roleDefinitionId'))]",
                "principalId": "[parameters('principalId')]",
                "scope": "[subscriptionResourceId('Microsoft.Resources/resourceGroups', parameters('rgName'))]"
              }
            }
          ]
        }
      }
    }
  ]
}

后续步骤Next steps