如何将托管标识与 Azure 容器实例结合使用How to use managed identities with Azure Container Instances

使用 Azure 资源的托管标识在 Azure 容器实例中运行代码以便与其他 Azure 服务交互,而无需在代码中维护任何机密或凭据。Use managed identities for Azure resources to run code in Azure Container Instances that interacts with other Azure services - without maintaining any secrets or credentials in code. 该功能提供了 Azure 容器实例部署,在 Azure Active Directory 中有一个自动托管标识。The feature provides an Azure Container Instances deployment with an automatically managed identity in Azure Active Directory.

本文将介绍有关 Azure 容器实例中托管标识的详细信息以及:In this article, you learn more about managed identities in Azure Container Instances and:

  • 在容器组中启用用户分配或系统分配的标识Enable a user-assigned or system-assigned identity in a container group
  • 授予标识对 Azure Key Vault 的访问权限Grant the identity access to an Azure key vault
  • 使用托管标识从正在运行的容器访问 Key VaultUse the managed identity to access a key vault from a running container

调整示例,以启用并使用 Azure 容器实例中的标识来访问其他 Azure 服务。Adapt the examples to enable and use identities in Azure Container Instances to access other Azure services. 这些示例是交互式的。These examples are interactive. 但实际上,容器映像将运行代码来访问 Azure 服务。However, in practice your container images would run code to access Azure services.

重要

此功能目前以预览版提供。This feature is currently in preview. 需同意补充使用条款才可使用预览版。Previews are made available to you on the condition that you agree to the supplemental terms of use. 在正式版 (GA) 推出之前,此功能的某些方面可能会有所更改。Some aspects of this feature may change prior to general availability (GA). 目前,仅 Linux 容器支持 Azure 容器实例上的托管标识。Currently, managed identities on Azure Container Instances, are only supported with Linux containers.

为什么使用托管标识?Why use a managed identity?

在运行的容器中使用托管标识,可对支持 Azure AD 身份验证的任何服务进行身份验证,而无需在容器代码中管理凭据。Use a managed identity in a running container to authenticate to any service that supports Azure AD authentication without managing credentials in your container code. 对于不支持 AD 身份验证的服务,可以在 Azure Key Vault 中存储机密并使用托管标识来访问 Key Vault 以检索凭据。For services that don't support AD authentication, you can store secrets in an Azure key vault and use the managed identity to access the key vault to retrieve credentials. 有关使用托管标识的详细信息,请参阅什么是 Azure 资源的托管标识?For more information about using a managed identity, see What is managed identities for Azure resources?

启用托管标识Enable a managed identity

创建容器组时,可通过设置 ContainerGroupIdentity 属性来启用一个或多个托管标识。When you create a container group, enable one or more managed identities by setting a ContainerGroupIdentity property. 还可以在容器组运行后启用或更新托管标识;任何一个操作都会导致容器组重启。You can also enable or update managed identities after a container group is running - either action causes the container group to restart. 若要在新容器组或现有容器组上设置标识,请使用 Azure CLI、资源管理器模板、YAML 文件或其他 Azure 工具。To set the identities on a new or existing container group, use the Azure CLI, a Resource Manager template, a YAML file, or another Azure tool.

Azure 容器实例支持以下两种类型的 Azure 托管标识:用户分配和系统分配。Azure Container Instances supports both types of managed Azure identities: user-assigned and system-assigned. 在容器组中,可以启用系统分配的标识、一个或多个用户分配的标识或这两种类型的标识。On a container group, you can enable a system-assigned identity, one or more user-assigned identities, or both types of identities. 如果不熟悉 Azure 资源的托管标识,请参阅概述If you're unfamiliar with managed identities for Azure resources, see the overview.

使用托管标识Use a managed identity

若要使用托管标识,必须授予标识对订阅中一个或多个 Azure 服务资源(例如 Web 应用、密钥保管库或存储帐户)的访问权限。To use a managed identity, the identity must be granted access to one or more Azure service resources (such as a web app, a key vault, or a storage account) in the subscription. 在正在运行的容器中使用托管标识与在 Azure VM 中使用标识相似。Using a managed identity in a running container is similar to using an identity in an Azure VM. 请参阅有关使用令牌Azure PowerShell 或 Azure CLIAzure SDK 的 VM 指南。See the VM guidance for using a token, Azure PowerShell or Azure CLI, or the Azure SDKs.

限制Limitations

  • 目前不能在部署到虚拟网络的容器组中使用托管标识。Currently you can't use a managed identity in a container group deployed to a virtual network.
  • 创建容器组时,不能使用托管标识从 Azure 容器注册表中拉取映像。You can't use a managed identity to pull an image from Azure Container Registry when creating a container group. 该标识仅在正在运行的容器中可用。The identity is only available within a running container.

备注

在 Azure China 中使用 Azure CLI 2.0 之前,请首先运行 az cloud set -n AzureChinaCloud 更改云环境。Before you can use Azure CLI 2.0 in Azure China, please run az cloud set -n AzureChinaCloud first to change the cloud environment. 如果要切换回全局 Azure,请再次运行 az cloud set -n AzureCloudIf you want to switch back to Global Azure, run az cloud set -n AzureCloud again.

如果选择在本地安装并使用 CLI,本文要求运行 Azure CLI 2.0.49 或更高版本。If you choose to install and use the CLI locally, this article requires that you are running the Azure CLI version 2.0.49 or later. 运行 az --version 即可查找版本。Run az --version to find the version. 如果需要进行安装或升级,请参阅安装 Azure CLIIf you need to install or upgrade, see Install Azure CLI.

创建 Azure Key VaultCreate an Azure key vault

本文中示例使用 Azure 容器实例中的托管标识来访问 Azure Key Vault 机密。The examples in this article use a managed identity in Azure Container Instances to access an Azure key vault secret.

首先,使用以下 az group create 命令在 chinaeast2 位置中创建一个名为“myResourceGroup”的资源组:First, create a resource group named myResourceGroup in the chinaeast2 location with the following az group create command:

az group create --name myResourceGroup --location chinaeast2

使用 az keyvault create 命令创建 Key Vault。Use the az keyvault create command to create a key vault. 请务必指定唯一的 Key Vault 名称。Be sure to specify a unique key vault name.

az keyvault create \
  --name mykeyvault \
  --resource-group myResourceGroup \ 
  --location chinaeast2

使用 az keyvault secret set 命令在 Key Vault 中存储实例机密:Store a sample secret in the key vault using the az keyvault secret set command:

az keyvault secret set \
  --name SampleSecret \
  --value "Hello Container Instances" \
  --description ACIsecret --vault-name mykeyvault

继续下面的示例,使用 Azure 容器实例中用户分配或系统分配的托管标识访问 Key Vault。Continue with the following examples to access the key vault using either a user-assigned or system-assigned managed identity in Azure Container Instances.

示例 1:使用用户分配的标识访问 Azure Key VaultExample 1: Use a user-assigned identity to access Azure key vault

创建标识Create an identity

首先使用 az identity create 命令在订阅中创建标识。First create an identity in your subscription using the az identity create command. 可以使用用于创建 Key Vault 的相同资源组,也可以使用不同的资源组。You can use the same resource group used to create the key vault, or use a different one.

az identity create \
  --resource-group myResourceGroup \
  --name myACIId

若要在以下步骤中使用标识,请使用 az identity show 命令在变量中存储标识的服务主体 ID 和资源 ID。To use the identity in the following steps, use the az identity show command to store the identity's service principal ID and resource ID in variables.

# Get service principal ID of the user-assigned identity
spID=$(az identity show \
  --resource-group myResourceGroup \
  --name myACIId \
  --query principalId --output tsv)

# Get resource ID of the user-assigned identity
resourceID=$(az identity show \
  --resource-group myResourceGroup \
  --name myACIId \
  --query id --output tsv)

授予用户分配的标识对 Key Vault 的访问权限Grant user-assigned identity access to the key vault

运行以下 az keyvault set-policy 命令来设置对 Key Vault 的访问策略。Run the following az keyvault set-policy command to set an access policy on the key vault. 以下示例允许用户分配的标识从 Key Vault 中获取机密:The following example allows the user-assigned identity to get secrets from the key vault:

 az keyvault set-policy \
    --name mykeyvault \
    --resource-group myResourceGroup \
    --object-id $spID \
    --secret-permissions get

在容器组中启用用户分配的标识Enable user-assigned identity on a container group

运行以下 az container create 命令基于 Azure 的 azure-cli 映像创建容器实例。Run the following az container create command to create a container instance based on Azure's azure-cli image. 此示例提供了单一容器组,可用于以交互方式运行 Azure CLI 以访问其他 Azure 服务。This example provides a single-container group that you can use interactively to run the Azure CLI to access other Azure services. 在本部分中,只使用基本操作系统。In this section, only the base operating system is used. 有关在容器中使用 Azure CLI 的示例,请参阅在容器组中启用系统分配的标识For an example to use the Azure CLI in the container, see Enable system-assigned identity on a container group.

--assign-identity 参数将用户分配的托管标识传递到组。The --assign-identity parameter passes your user-assigned managed identity to the group. 长时间运行命令将使容器保持运行状态。The long-running command keeps the container running. 此示例使用用于创建 Key Vault 的相同资源组,但可以指定不同的资源组。This example uses the same resource group used to create the key vault, but you could specify a different one.

az container create \
  --resource-group myResourceGroup \
  --name mycontainer \
  --image mcr.microsoft.com/azure-cli \
  --assign-identity $resourceID \
  --command-line "tail -f /dev/null"

在几秒钟内,你应当会从 Azure CLI 收到响应,它指出部署已完成。Within a few seconds, you should get a response from the Azure CLI indicating that the deployment has completed. 使用 az container show 命令检查它的状态。Check its status with the az container show command.

az container show \
  --resource-group myResourceGroup \
  --name mycontainer

输出的 identity 部分类似于以下内容,显示在容器组中设置的标识。The identity section in the output looks similar to the following, showing the identity is set in the container group. userAssignedIdentities 下的 principalID 是在 Azure Active Directory 中创建的标识的服务主体:The principalID under userAssignedIdentities is the service principal of the identity you created in Azure Active Directory:

[...]
"identity": {
    "principalId": "null",
    "tenantId": "xxxxxxxx-f292-4e60-9122-xxxxxxxxxxxx",
    "type": "UserAssigned",
    "userAssignedIdentities": {
      "/subscriptions/xxxxxxxx-0903-4b79-a55a-xxxxxxxxxxxx/resourcegroups/danlep1018/providers/Microsoft.ManagedIdentity/userAssignedIdentities/myACIId": {
        "clientId": "xxxxxxxx-5523-45fc-9f49-xxxxxxxxxxxx",
        "principalId": "xxxxxxxx-f25b-4895-b828-xxxxxxxxxxxx"
      }
    }
  },
[...]

使用用户分配的标识从 Key Vault 中获取机密Use user-assigned identity to get secret from key vault

现在可以使用正在运行的容器实例中的托管标识来访问 Key Vault。Now you can use the managed identity within the running container instance to access the key vault. 首先在容器中启动 bash shell:First launch a bash shell in the container:

az container exec \
  --resource-group myResourceGroup \
  --name mycontainer \
  --exec-command "/bin/bash"

在容器的 bash shell 中运行以下命令。Run the following commands in the bash shell in the container. 若要获取访问令牌以使用 Azure Active Directory 对 Key Vault 进行身份验证,请运行以下命令:To get an access token to use Azure Active Directory to authenticate to key vault, run the following command:

curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.cn' -H Metadata:true -s

输出:Output:

{"access_token":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Imk2bEdrM0ZaenhSY1ViMkMzbkVRN3N5SEpsWSIsImtpZCI6Imk2bEdrM0ZaenhSY1ViMkMzbkVRN3N5SEpsWSJ9......xxxxxxxxxxxxxxxxx","refresh_token":"","expires_in":"28799","expires_on":"1539927532","not_before":"1539898432","resource":"https://vault.azure.cn/","token_type":"Bearer"}

若要在变量中存储访问令牌以便在后续命令中进行身份验证,运行以下命令:To store the access token in a variable to use in subsequent commands to authenticate, run the following command:

token=$(curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fvault.azure.cn' -H Metadata:true | jq -r '.access_token')

现在使用访问令牌对密钥保管库进行身份验证并读取机密。Now use the access token to authenticate to key vault and read a secret. 请确保在 URL (https://mykeyvault.vault.azure.cn/...) 中替换你的密钥保管库名称:Be sure to substitute the name of your key vault in the URL (https://mykeyvault.vault.azure.cn/...):

curl https://mykeyvault.vault.azure.cn/secrets/SampleSecret/?api-version=2016-10-01 -H "Authorization: Bearer $token"

响应类似于以下内容,其中显示机密。The response looks similar to the following, showing the secret. 在代码中,将分析此输出,以便获取机密。In your code, you would parse this output to obtain the secret. 然后,在后续操作中使用机密来访问另一个 Azure 资源。Then, use the secret in a subsequent operation to access another Azure resource.

{"value":"Hello Container Instances","contentType":"ACIsecret","id":"https://mykeyvault.vault.azure.cn/secrets/SampleSecret/xxxxxxxxxxxxxxxxxxxx","attributes":{"enabled":true,"created":1539965967,"updated":1539965967,"recoveryLevel":"Purgeable"},"tags":{"file-encoding":"utf-8"}}

示例 2:使用系统分配的标识访问 Azure Key VaultExample 2: Use a system-assigned identity to access Azure key vault

在容器组中启用系统分配的标识Enable system-assigned identity on a container group

运行以下 az container create 命令基于 Azure 的 azure-cli 映像创建容器实例。Run the following az container create command to create a container instance based on Azure's azure-cli image. 此示例提供了单一容器组,可用于以交互方式运行 Azure CLI 以访问其他 Azure 服务。This example provides a single-container group that you can use interactively to run the Azure CLI to access other Azure services.

没有任何附加值的 --assign-identity 参数在组上启用系统分配的托管标识。The --assign-identity parameter with no additional value enables a system-assigned managed identity on the group. 标识的范围限定为容器组的资源组。The identity is scoped to the resource group of the container group. 长时间运行命令将使容器保持运行状态。The long-running command keeps the container running. 此示例使用用于创建密钥保管库的相同资源组,该资源组在此标识的范围内。This example uses the same resource group used to create the key vault, which is in the scope of the identity.

# Get the resource ID of the resource group
rgID=$(az group show --name myResourceGroup --query id --output tsv)

# Create container group with system-managed identity
az container create \
  --resource-group myResourceGroup \
  --name mycontainer \
  --image mcr.microsoft.com/azure-cli \
  --assign-identity --scope $rgID \
  --command-line "tail -f /dev/null"

在几秒钟内,你应当会从 Azure CLI 收到响应,它指出部署已完成。Within a few seconds, you should get a response from the Azure CLI indicating that the deployment has completed. 使用 az container show 命令检查它的状态。Check its status with the az container show command.

az container show \
  --resource-group myResourceGroup \
  --name mycontainer

输出中的 identity 部分类似于以下内容,其中显示系统分配的标识在 Azure Active Directory 中创建:The identity section in the output looks similar to the following, showing that a system-assigned identity is created in Azure Active Directory:

[...]
"identity": {
    "principalId": "xxxxxxxx-528d-7083-b74c-xxxxxxxxxxxx",
    "tenantId": "xxxxxxxx-f292-4e60-9122-xxxxxxxxxxxx",
    "type": "SystemAssigned",
    "userAssignedIdentities": null
},
[...]

将变量设置为标识的值 principalId(服务主体 ID),以便在后续步骤中使用。Set a variable to the value of principalId (the service principal ID) of the identity, to use in later steps.

spID=$(az container show \
  --resource-group myResourceGroup \
  --name mycontainer \
  --query identity.principalId --out tsv)

授予容器组对 Key Vault 的访问权限Grant container group access to the key vault

运行以下 az keyvault set-policy 命令来设置对 Key Vault 的访问策略。Run the following az keyvault set-policy command to set an access policy on the key vault. 以下示例允许系统托管标识从 Key Vault 中获取机密:The following example allows the system-managed identity to get secrets from the key vault:

 az keyvault set-policy \
   --name mykeyvault \
   --resource-group myResourceGroup \
   --object-id $spID \
   --secret-permissions get

使用容器组标识从 Key Vault 中获取机密Use container group identity to get secret from key vault

现在可以使用托管标识来访问正在运行的容器实例中的 Key Vault。Now you can use the managed identity to access the key vault within the running container instance. 首先在容器中启动 bash shell:First launch a bash shell in the container:

az container exec \
  --resource-group myResourceGroup \
  --name mycontainer \
  --exec-command "/bin/bash"

在容器的 bash shell 中运行以下命令。Run the following commands in the bash shell in the container. 首先使用托管标识登录到 Azure CLI:First log in to the Azure CLI using the managed identity:

az cloud set -n AzureChinaCloud
az login --identity

从正在运行的容器中检索 Key Vault 中的机密:From the running container, retrieve the secret from the key vault:

az keyvault secret show \
  --name SampleSecret \
  --vault-name mykeyvault --query value

此时会检索机密值:The value of the secret is retrieved:

"Hello Container Instances"

使用资源管理器模板启用托管标识Enable managed identity using Resource Manager template

若要使用资源管理器模板在容器组中启用托管标识,请使用 ContainerGroupIdentity 对象设置 Microsoft.ContainerInstance/containerGroups 对象的 identity 属性。To enable a managed identity in a container group using a Resource Manager template, set the identity property of the Microsoft.ContainerInstance/containerGroups object with a ContainerGroupIdentity object. 下面的代码段演示针对不同方案配置的 identity 属性。The following snippets show the identity property configured for different scenarios. 指定最小的 apiVersion,即 2018-10-01Specify a minimum apiVersion of 2018-10-01.

用户分配的标识User-assigned identity

用户分配的标识是窗体的资源 ID:A user-assigned identity is a resource ID of the form:

"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}"

可以启用一个或多个用户分配的标识。You can enable one or more user-assigned identities.

"identity": {
    "type": "UserAssigned",
    "userAssignedIdentities": {
        "myResourceID1": {
            }
        }
    }

系统分配的标识System-assigned identity

"identity": {
    "type": "SystemAssigned"
    }

系统和用户分配的标识System- and user-assigned identities

在容器组中,可以同时启用系统分配的标识和一个或多个用户分配的标识。On a container group, you can enable both a system-assigned identity and one or more user-assigned identities.

"identity": {
    "type": "System Assigned, UserAssigned",
    "userAssignedIdentities": {
        "myResourceID1": {
            }
        }
    }
...

使用 YAML 文件启用托管标识Enable managed identity using YAML file

若要在使用 YAML 文件部署的容器组中启用托管标识,请包含以下 YAML。To enable a managed identity in a container group deployed using a YAML file, include the following YAML. 指定最小的 apiVersion,即 2018-10-01Specify a minimum apiVersion of 2018-10-01.

用户分配的标识User-assigned identity

用户分配的标识是窗体的资源 IDA user-assigned identity is a resource ID of the form

'/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'

可以启用一个或多个用户分配的标识。You can enable one or more user-assigned identities.

identity:
  type: UserAssigned
  userAssignedIdentities:
    {'myResourceID1':{}}

系统分配的标识System-assigned identity

identity:
  type: SystemAssigned

系统和用户分配的标识System- and user-assigned identities

在容器组中,可以同时启用系统分配的标识和一个或多个用户分配的标识。On a container group, you can enable both a system-assigned identity and one or more user-assigned identities.

identity:
  type: SystemAssigned, UserAssigned
  userAssignedIdentities:
   {'myResourceID1':{}}

后续步骤Next steps

本文将介绍有关 Azure 容器实例中托管标识的信息以及如何:In this article, you learned about managed identities in Azure Container Instances and how to:

  • 在容器组中启用用户分配或系统分配的标识Enable a user-assigned or system-assigned identity in a container group
  • 授予标识对 Azure Key Vault 的访问权限Grant the identity access to an Azure key vault
  • 使用托管标识从正在运行的容器访问 Key VaultUse the managed identity to access a key vault from a running container