在容器实例中设置环境变量Set environment variables in container instances

通过在容器实例中设置环境变量,可为容器运行的应用程序或脚本提供动态配置。Setting environment variables in your container instances allows you to provide dynamic configuration of the application or script run by the container. 这类似于在 --env 命令行中指定参数 docker runThis is similar to the --env command-line argument to docker run.

若要设置容器中的环境变量,请在创建容器实例时进行指定。To set environment variables in a container, specify them when you create a container instance. 本文演示的示例介绍了如何在使用 Azure CLIAzure PowerShellAzure 门户启动容器时设置环境变量。This article shows examples of setting environment variables when you start a container with the Azure CLI, Azure PowerShell, and the Azure portal.

例如,如果运行 Microsoft aci-wordcount 容器映像,可以通过指定以下环境变量来修改其行为:For example, if you run the Microsoft aci-wordcount container image, you can modify its behavior by specifying the following environment variables:

NumWords:发送到 STDOUT 的单词数。NumWords: The number of words sent to STDOUT.

MinLength:单词中最少包含几个字符才将它统计为一个单词。MinLength: The minimum number of characters in a word for it to be counted. 如果指定较大的数字,将会忽略“of”和“the”等常见单词。A higher number ignores common words like "of" and "the."

如果需要以环境变量的形式传递机密,Azure 容器实例支持 Linux 容器的安全值If you need to pass secrets as environment variables, Azure Container Instances supports secure values for Linux containers.

备注

本文进行了更新,以便使用新的 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.

Azure CLI 示例Azure CLI example

若要查看 aci-wordcount 容器的默认输出,请首先使用此 az container create 命令来运行它(不指定环境变量):To see the default output of the aci-wordcount container, run it first with this az container create command (no environment variables specified):

az container create \
    --resource-group myResourceGroup \
    --name mycontainer1 \
    --image mcr.microsoft.com/azuredocs/aci-wordcount:latest \
    --restart-policy OnFailure

若要修改输出,请在添加 --environment-variables 变量的情况下启动又一个容器,为 NumWordsMinLength 变量指定值。To modify the output, start a second container with the --environment-variables argument added, specifying values for the NumWords and MinLength variables. (此示例假定在 Bash shell 中运行 CLI。(This example assume you are running the CLI in a Bash shell . 如果使用 Windows 命令提示符,请使用双引号指定变量,例如 --environment-variables "NumWords"="5" "MinLength"="8"。)If you use the Windows Command Prompt, specify the variables with double-quotes, such as --environment-variables "NumWords"="5" "MinLength"="8".)

az container create \
    --resource-group myResourceGroup \
    --name mycontainer2 \
    --image mcr.microsoft.com/azuredocs/aci-wordcount:latest \
    --restart-policy OnFailure \
    --environment-variables 'NumWords'='5' 'MinLength'='8'

两个容器的状态显示为“已终止”后 (使用 az container show 来查看状态),请使用 az container logs 来显示其日志,以便查看输出。Once both containers' state shows as Terminated (use az container show to check state), display their logs with az container logs to see the output.

az container logs --resource-group myResourceGroup --name mycontainer1
az container logs --resource-group myResourceGroup --name mycontainer2

容器的输出显示你如何通过设置环境变量修改了第二个容器的脚本行为。The output of the containers show how you've modified the second container's script behavior by setting environment variables.

mycontainer1mycontainer1

[('the', 990),
 ('and', 702),
 ('of', 628),
 ('to', 610),
 ('I', 544),
 ('you', 495),
 ('a', 453),
 ('my', 441),
 ('in', 399),
 ('HAMLET', 386)]

mycontainer2mycontainer2

[('CLAUDIUS', 120),
 ('POLONIUS', 113),
 ('GERTRUDE', 82),
 ('ROSENCRANTZ', 69),
 ('GUILDENSTERN', 54)]

Azure PowerShell 示例Azure PowerShell example

在 PowerShell 中设置环境变量类似于在 CLI 中进行的相应操作,但需使用 -EnvironmentVariable 命令行参数。Setting environment variables in PowerShell is similar to the CLI, but uses the -EnvironmentVariable command-line argument.

首先,使用此 New-AzContainerGroup 命令在默认配置中启动 aci-wordcount 容器:First, launch the aci-wordcount container in its default configuration with this New-AzContainerGroup command:

New-AzContainerGroup `
    -ResourceGroupName myResourceGroup `
    -Name mycontainer1 `
    -Image mcr.microsoft.com/azuredocs/aci-wordcount:latest

现在请运行以下 New-AzContainerGroup 命令。Now run the following New-AzContainerGroup command. 此命令在填充数组变量 envVars 后指定 NumWordsMinLength 环境变量:This one specifies the NumWords and MinLength environment variables after populating an array variable, envVars:

$envVars = @{'NumWords'='5';'MinLength'='8'}
New-AzContainerGroup `
    -ResourceGroupName myResourceGroup `
    -Name mycontainer2 `
    -Image mcr.microsoft.com/azuredocs/aci-wordcount:latest `
    -RestartPolicy OnFailure `
    -EnvironmentVariable $envVars

两个容器的状态均为“已终止”后 (使用 Get-AzContainerInstanceLog 来查看状态),请使用 Get-AzContainerInstanceLog 命令来拉取其日志。Once both containers' state is Terminated (use Get-AzContainerInstanceLog to check state), pull their logs with the Get-AzContainerInstanceLog command.

Get-AzContainerInstanceLog -ResourceGroupName myResourceGroup -ContainerGroupName mycontainer1
Get-AzContainerInstanceLog -ResourceGroupName myResourceGroup -ContainerGroupName mycontainer2

每个容器的输出显示你如何通过设置环境变量修改了容器运行的脚本。The output for each container shows how you've modified the script run by the container by setting environment variables.

PS Azure:\> Get-AzContainerInstanceLog -ResourceGroupName myResourceGroup -ContainerGroupName mycontainer1
[('the', 990),
 ('and', 702),
 ('of', 628),
 ('to', 610),
 ('I', 544),
 ('you', 495),
 ('a', 453),
 ('my', 441),
 ('in', 399),
 ('HAMLET', 386)]

Azure:\
PS Azure:\> Get-AzContainerInstanceLog -ResourceGroupName myResourceGroup -ContainerGroupName mycontainer2
[('CLAUDIUS', 120),
 ('POLONIUS', 113),
 ('GERTRUDE', 82),
 ('ROSENCRANTZ', 69),
 ('GUILDENSTERN', 54)]

Azure:\

Azure 门户示例Azure portal example

在 Azure 门户中启动容器时,若要设置环境变量,请在创建容器时所在的“高级”页中指定它们。 To set environment variables when you start a container in the Azure portal, specify them in the Advanced page when you create the container.

  1. 在“高级”页上将“重启策略”设置为“在故障时” On the Advanced page, set the Restart policy to On failure
  2. 在“环境变量”下,为第一个变量输入值为 5NumWords,并为第二个变量输入值为 8MinLengthUnder Environment variables, enter NumWords with a value of 5 for the first variable, and enter MinLength with a value of 8 for the second variable.
  3. 选择“查看 + 创建”进行验证,然后部署容器。 Select Review + create to verify and then deploy the container.

门户页,显示环境变量“启用”按钮和文本框

若要查看容器的日志,请在“设置” 下选择“容器” ,然后选择“日志” 。To view the container's logs, under Settings select Containers, then Logs. 可以查看通过环境变量对脚本行为进行的具体修改,这与在此前的 CLI 和 PowerShell 部分显示的输出类似。Similar to the output shown in the previous CLI and PowerShell sections, you can see how the script's behavior has been modified by the environment variables. 仅显示了五个单词,每个的最小长度为八个字符。Only five words are displayed, each with a minimum length of eight characters.

显示容器日志输出的门户

安全值Secure values

具有安全值的对象旨在为应用程序保留密码或密钥等敏感信息。Objects with secure values are intended to hold sensitive information like passwords or keys for your application. 对环境变量使用安全值比将它添加到容器映像中更为安全灵活。Using secure values for environment variables is both safer and more flexible than including it in your container's image. 也可以使用机密卷,如在 Azure 容器实例中装载机密卷所述。Another option is to use secret volumes, described in Mount a secret volume in Azure Container Instances.

具有安全值的环境变量在容器的属性中不可见 - 它们的值只能从容器中访问。Environment variables with secure values aren't visible in your container's properties--their values can be accessed only from within the container. 例如,在 Azure 门户或 Azure CLI 中查看的容器属性仅显示安全变量的名称,而不显示其值。For example, container properties viewed in the Azure portal or Azure CLI display only a secure variable's name, not its value.

安全环境变量的设置方法为,指定 secureValue 属性(而不是常规 value)作为变量类型。Set a secure environment variable by specifying the secureValue property instead of the regular value for the variable's type. 下面 YAML 中定义的两个变量展示了两种变量类型。The two variables defined in the following YAML demonstrate the two variable types.

YAML 部署YAML deployment

创建包含下面的代码片段的 secure-env.yaml 文件。Create a secure-env.yaml file with the following snippet.

apiVersion: 2018-10-01
location: chinaeast2
name: securetest
properties:
  containers:
  - name: mycontainer
    properties:
      environmentVariables:
        - name: 'NOTSECRET'
          value: 'my-exposed-value'
        - name: 'SECRET'
          secureValue: 'my-secret-value'
      image: nginx
      ports: []
      resources:
        requests:
          cpu: 1.0
          memoryInGB: 1.5
  osType: Linux
  restartPolicy: Always
tags: null
type: Microsoft.ContainerInstance/containerGroups

运行以下命令以使用 YAML 部署容器组(根据需要调整资源组名称):Run the following command to deploy the container group with YAML (adjust the resource group name as necessary):

az container create --resource-group myResourceGroup --file secure-env.yaml

验证环境变量Verify environment variables

运行 az container show 命令查询容器的环境变量:Run the az container show command to query your container's environment variables:

az container show --resource-group myResourceGroup --name securetest --query 'containers[].environmentVariables'

JSON 响应显示不安全的环境变量的键和值,但仅显示安全环境变量的名称:The JSON response shows both the insecure environment variable's key and value, but only the name of the secure environment variable:

[
  [
    {
      "name": "NOTSECRET",
      "secureValue": null,
      "value": "my-exposed-value"
    },
    {
      "name": "SECRET",
      "secureValue": null,
      "value": null
    }
  ]
]

使用 az container exec 命令(允许在正在运行的容器中执行命令),可以验证是否已设置安全环境变量。With the az container exec command, which enables executing a command in a running container, you can verify that the secure environment variable has been set. 运行以下命令以在容器中启动交互式 bash 会话:Run the following command to start an interactive bash session in the container:

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

在容器中打开交互式 shell 后,可以访问 SECRET 变量的值:Once you've opened an interactive shell within the container, you can access the SECRET variable's value:

root@caas-ef3ee231482549629ac8a40c0d3807fd-3881559887-5374l:/# echo $SECRET
my-secret-value

后续步骤Next steps

基于任务的方案(例如对使用多个容器的数据库进行批处理)可以在运行时充分利用自定义环境变量。Task-based scenarios, such as batch processing a large dataset with several containers, can benefit from custom environment variables at runtime. 若要详细了解如何运行基于任务的容器,请参阅使用重启策略运行容器化任务For more information about running task-based containers, see Run containerized tasks with restart policies.