您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

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

通常情况下,你可将 Azure 资源部署到 Azure 订阅中的资源组。Typically, you deploy Azure resources to a resource group in your Azure subscription. 但是,你还可以创建 Azure 资源组,并在订阅级别创建 Azure 资源。However, you can also create Azure resource groups, and create Azure resources at the subscription level. 若要在订阅级别部署模板,请使用 Azure CLI 和 Azure PowerShell。To deploy templates at the subscription level, you use Azure CLI and Azure PowerShell. Azure 门户不支持在订阅级别部署。The Azure portal doesn't support deployment in the subscription level.

若要在 Azure 资源管理器模板中创建资源组,请为该资源组定义包含名称和位置的 Microsoft.Resources/resourceGroups 资源。To create a resource group in an Azure Resource Manager template, define a Microsoft.Resources/resourceGroups resource with a name and location for the resource group. 你可以创建一个资源组并在同一模板中将资源部署到该资源组。You can create a resource group and deploy resources to that resource group in the same template. 可以在订阅级别部署的资源包括:策略基于角色的访问控制The resources that you can deploy at the subscription level include: Policies, and Role-based access control.

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

部署注意事项Deployment considerations

订阅级别部署与资源组部署的不同之处有以下几个方面:Subscription level deployment is different from resource group deployment in the following aspects:

架构和命令Schema and commands

用于订阅级部署的架构和命令不同于资源组部署。The schema and commands you use for subscription-level deployments are different than resource group deployments.

对于架构,请使用 https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#For the schema, use https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#.

对于 Azure CLI 部署命令,请使用 az deployment createFor the Azure CLI deployment command, use az deployment create. 例如,以下 CLI 命令部署模板以创建资源组:For example, the following CLI command deploys a template to create a resource group:

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

对于 PowerShell 部署命令,请使用 New-AzDeploymentFor the PowerShell deployment command, use New-AzDeployment. 例如,以下 PowerShell 命令部署模板以创建资源组:For example, the following PowerShell command deploys a template to create a resource group:

New-AzDeployment `
  -Name demoDeployment `
  -Location centralus `
  -TemplateUri https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/emptyRG.json `
  -rgName demoResourceGroup `
  -rgLocation centralus

部署名称和位置Deployment name and location

部署到订阅时,必须为部署提供位置。When deploying to your subscription, you must provide a location for the deployment. 还可以为部署提供名称。You can also provide a name for the deployment. 如果没有为部署指定名称,则会将模板的名称用作部署名称。If you don't specify a name for the deployment, the name of the template is used as the deployment name. 例如,部署一个名为 azuredeploy.json 的模板将创建默认部署名称 azuredeployFor example, deploying a template named azuredeploy.json creates a default deployment name of azuredeploy.

订阅级部署的位置不可改变。The location of subscription level deployments is immutable. 当某个位置中已有某个部署时,无法在另一位置创建同名的部署。You can't create a deployment in one location when there's an existing deployment with the same name but 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.

使用模板函数Use template functions

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

  • 不支持 resourceGroup() 函数。 The resourceGroup() function is not supported.
  • 支持 resourceId() 函数。The resourceId() function is supported. 可以使用它获取在订阅级部署中使用的资源的资源 ID。Use it to get the resource ID for resources that are used at subscription level deployments. 例如,使用 resourceId('Microsoft.Authorization/roleDefinitions/', parameters('roleDefinition')) 获取策略定义的资源 IDFor example, get the resource ID for a policy definition with resourceId('Microsoft.Authorization/roleDefinitions/', parameters('roleDefinition'))
  • 支持 reference()list() 函数。The reference() and list() functions are supported.

创建资源组Create resource groups

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

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

模板架构可在此处找到。The template schema can be found at here. 类似模板可在 GitHub 找到。Similar templates can be found at GitHub.

创建多个资源组Create multiple resource groups

结合使用 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.1",
    "parameters": {
        "rgNamePrefix": {
            "type": "string"
        },
        "rgLocation": {
            "type": "string"
        },
        "instanceCount": {
            "type": "int"
        }
    },
    "variables": {},
    "resources": [
        {
            "type": "Microsoft.Resources/resourceGroups",
            "apiVersion": "2018-05-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 or property in Azure Resource Manager Templates, and Tutorial: Create multiple resource instances with Resource Manager templates.

创建资源组并部署资源Create resource group and deploy 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.

以下示例将创建一个资源组,并向该资源组部署存储帐户。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.1",
    "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": "2018-05-01",
            "location": "[parameters('rgLocation')]",
            "name": "[parameters('rgName')]",
            "properties": {}
        },
        {
            "type": "Microsoft.Resources/deployments",
            "apiVersion": "2018-05-01",
            "name": "storageDeployment",
            "resourceGroup": "[parameters('rgName')]",
            "dependsOn": [
                "[resourceId('Microsoft.Resources/resourceGroups/', parameters('rgName'))]"
            ],
            "properties": {
                "mode": "Incremental",
                "template": {
                    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                    "contentVersion": "1.0.0.0",
                    "parameters": {},
                    "variables": {},
                    "resources": [
                        {
                            "type": "Microsoft.Storage/storageAccounts",
                            "apiVersion": "2017-10-01",
                            "name": "[variables('storageName')]",
                            "location": "[parameters('rgLocation')]",
                            "kind": "StorageV2",
                            "sku": {
                                "name": "Standard_LRS"
                            }
                        }
                    ],
                    "outputs": {}
                }
            }
        }
    ],
    "outputs": {}
}

创建策略Create policies

分配策略Assign policy

以下示例将现有的策略定义分配到订阅。The following example assigns an existing policy definition to the subscription. 如果策略使用参数,请将参数作为对象提供。If the policy takes parameters, provide them as an object. 如果策略不使用参数,请使用默认的空对象。If the policy 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",
            "name": "[parameters('policyName')]",
            "apiVersion": "2018-03-01",
            "properties": {
                "scope": "[subscription().id]",
                "policyDefinitionId": "[parameters('policyDefinitionID')]",
                "parameters": "[parameters('policyParameters')]"
            }
        }
    ]
}

若要向 Azure 订阅应用内置策略,请使用以下 Azure CLI 命令:To apply a built-in policy to your Azure subscription, use the following Azure CLI commands:

# Built-in policy that does not accept parameters
definition=$(az policy definition list --query "[?displayName=='Audit resource location matches resource group location'].id" --output tsv)

az deployment create \
  --name demoDeployment \
  --location centralus \
  --template-uri https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/policyassign.json \
  --parameters policyDefinitionID=$definition policyName=auditRGLocation

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

$definition = Get-AzPolicyDefinition | Where-Object { $_.Properties.DisplayName -eq 'Audit resource location matches resource group location' }

New-AzDeployment `
  -Name policyassign `
  -Location centralus `
  -TemplateUri https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/policyassign.json `
  -policyDefinitionID $definition.PolicyDefinitionId `
  -policyName auditRGLocation

若要向 Azure 订阅应用内置策略,请使用以下 Azure CLI 命令:To apply a built-in policy to your Azure subscription, use the following Azure CLI commands:

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

az deployment create \
  --name demoDeployment \
  --location centralus \
  --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': ['westus']} }"

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

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

$locations = @("westus", "westus2")
$policyParams =@{listOfAllowedLocations = @{ value = $locations}}

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

定义和分配策略Define and assign policy

可以在同一模板中定义和分配策略。You can define and assign a policy 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",
            "name": "locationpolicy",
            "apiVersion": "2018-05-01",
            "properties": {
                "policyType": "Custom",
                "parameters": {},
                "policyRule": {
                    "if": {
                        "field": "location",
                        "equals": "northeurope"
                    },
                    "then": {
                        "effect": "deny"
                    }
                }
            }
        },
        {
            "type": "Microsoft.Authorization/policyAssignments",
            "name": "location-lock",
            "apiVersion": "2018-05-01",
            "dependsOn": [
                "locationpolicy"
            ],
            "properties": {
                "scope": "[subscription().id]",
                "policyDefinitionId": "[resourceId('Microsoft.Authorization/policyDefinitions', 'locationpolicy')]"
            }
        }
    ]
}

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

az deployment create \
  --name demoDeployment \
  --location centralus \
  --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-AzDeployment `
  -Name definePolicy `
  -Location centralus `
  -TemplateUri https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/policydefineandassign.json

创建角色Create roles

在订阅时分配角色Assign role at subscription

以下示例将角色分配给订阅的用户或组。The following example assigns a role to a user or group for the subscription. 在此示例中,没有为分配指定范围,因为范围自动设置为预订。In this example, you don't specify a scope for the assignment because the scope is automatically set to the subscription.

{
    "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "principalId": {
            "type": "string"
        },
        "roleDefinitionId": {
            "type": "string"
        }
    },
    "variables": {},
    "resources": [
        {
            "type": "Microsoft.Authorization/roleAssignments",
            "name": "[guid(parameters('principalId'), deployment().name)]",
            "apiVersion": "2017-09-01",
            "properties": {
                "roleDefinitionId": "[resourceId('Microsoft.Authorization/roleDefinitions', parameters('roleDefinitionId'))]",
                "principalId": "[parameters('principalId')]"
            }
        }
    ]
}

若要向订阅的角色分配 Active Directory 组,请使用以下 Azure CLI 命令:To assign an Active Directory group to a role for your subscription, use the following Azure CLI commands:

# Get ID of the role you want to assign
role=$(az role definition list --name Contributor --query [].name --output tsv)

# Get ID of the AD group to assign the role to
principalid=$(az ad group show --group demogroup --query objectId --output tsv)

az deployment create \
  --name demoDeployment \
  --location centralus \
  --template-uri https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/roleassign.json \
  --parameters principalId=$principalid roleDefinitionId=$role

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

$role = Get-AzRoleDefinition -Name Contributor

$adgroup = Get-AzADGroup -DisplayName demogroup

New-AzDeployment `
  -Name demoRole `
  -Location centralus `
  -TemplateUri https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/roleassign.json `
  -roleDefinitionId $role.Id `
  -principalId $adgroup.Id

在作用域分配角色Assign role at scope

以下订阅级别模板将角色分配给订阅中作用域为资源组的用户或组。The following subscription-level template assigns a role to a user or group that is scoped to a resource group within the subscription. 作用域必须等于或低于部署级别。The scope must be at or below the level of deployment. 你可以部署到订阅并指定作用域为该订阅中资源组的角色分配。You can deploy to a subscription and specify a role assignment scoped to a resource group within that subscription. 但是,无法部署到资源组并为该订阅指定角色分配作用域。However, you can't deploy to a resource group and specify a role assignment scope to the subscription.

若要在作用域分配角色,请使用嵌套部署。To assign the role at a scope, use a nested deployment. 请注意,资源组名称均在部署资源的属性和角色分配作用域属性中指定。Notice that the resource group name is specified both in the properties for the deployment resource and in the scope property of the role assignment.

{
    "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
    "contentVersion": "1.0.0.1",
    "parameters": {
        "principalId": {
            "type": "string"
        },
        "roleDefinitionId": {
            "type": "string"
        },
        "rgName": {
            "type": "string"
        }
    },
    "variables": {},
    "resources": [
        {
            "type": "Microsoft.Resources/deployments",
            "apiVersion": "2018-05-01",
            "name": "assignRole",
            "resourceGroup": "[parameters('rgName')]",
            "properties": {
                "mode": "Incremental",
                "template": {
                    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                    "contentVersion": "1.0.0.0",
                    "parameters": {},
                    "variables": {},
                    "resources": [
                        {
                            "type": "Microsoft.Authorization/roleAssignments",
                            "name": "[guid(parameters('principalId'), deployment().name)]",
                            "apiVersion": "2017-09-01",
                            "properties": {
                                "roleDefinitionId": "[resourceId('Microsoft.Authorization/roleDefinitions', parameters('roleDefinitionId'))]",
                                "principalId": "[parameters('principalId')]",
                                "scope": "[concat(subscription().id, '/resourceGroups/', parameters('rgName'))]"
                            }
                        }
                    ],
                    "outputs": {}
                }
            }
        }
    ],
    "outputs": {}
}

若要向订阅的角色分配 Active Directory 组,请使用以下 Azure CLI 命令:To assign an Active Directory group to a role for your subscription, use the following Azure CLI commands:

# Get ID of the role you want to assign
role=$(az role definition list --name Contributor --query [].name --output tsv)

# Get ID of the AD group to assign the role to
principalid=$(az ad group show --group demogroup --query objectId --output tsv)

az deployment create \
  --name demoDeployment \
  --location centralus \
  --template-uri https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/scopedRoleAssign.json \
  --parameters principalId=$principalid roleDefinitionId=$role rgName demoRg

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

$role = Get-AzRoleDefinition -Name Contributor

$adgroup = Get-AzADGroup -DisplayName demogroup

New-AzDeployment `
  -Name demoRole `
  -Location centralus `
  -TemplateUri https://raw.githubusercontent.com/Azure/azure-docs-json-samples/master/azure-resource-manager/scopedRoleAssign.json `
  -roleDefinitionId $role.Id `
  -principalId $adgroup.Id `
  -rgName demoRg

后续步骤Next steps