你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

用于 Python 的 Azure 容器实例库Azure Container Instances libraries for Python

使用用于 Python 的 Microsoft Azure 容器实例库来创建和管理 Azure 容器实例。Use the Microsoft Azure Container Instances libraries for Python to create and manage Azure container instances. 请阅读 Azure 容器实例概述,了解详细信息。Learn more by reading the Azure Container Instances overview.

管理 APIManagement APIs

使用管理库可在 Azure 中创建和管理 Azure 容器实例。Use the management library to create and manage Azure container instances in Azure.

通过 pip 安装管理包:Install the management package via pip:

pip install azure-mgmt-containerinstance

示例源Example source

若要在上下文中查看以下代码示例,可以在以下 GitHub 存储库中找到它们:If you'd like to see the following code examples in context, you can find them in the following GitHub repository:

Azure-Samples/aci-docs-sample-pythonAzure-Samples/aci-docs-sample-python

AuthenticationAuthentication

若要对 SDK 客户端进行身份验证(如以下示例中的 Azure 容器实例和资源管理器客户端),最容易的方式之一是使用基于文件的身份验证One of the easiest ways to authenticate SDK clients (like the Azure Container Instances and Resource Manager clients in the following example) is with file-based authentication. 基于文件的身份验证会查询 AZURE_AUTH_LOCATION 环境变量中是否存在凭据文件的路径。File-based authentication queries the AZURE_AUTH_LOCATION environment variable for the path to a credentials file. 若要使用基于文件的身份验证,请执行以下操作:To use file-based authentication:

  1. 使用 Azure CLICloud Shell 创建凭据文件:Create a credentials file with the Azure CLI or Cloud Shell:

    az ad sp create-for-rbac --sdk-auth > my.azureauth

    如果使用 Cloud Shell 生成凭据文件,请将其内容复制到 Python 应用程序能够访问的本地文件中。If you use the Cloud Shell to generate the credentials file, copy its contents into a local file that your Python application can access.

  2. AZURE_AUTH_LOCATION 环境变量设置为生成的凭据文件的完整路径。Set the AZURE_AUTH_LOCATION environment variable to the full path of the generated credentials file. 例如(在 Bash 中):For example (in Bash):

    export AZURE_AUTH_LOCATION=/home/yourusername/my.azureauth
    

创建凭据文件并填充 AZURE_AUTH_LOCATION 环境变量以后,请使用 client_factory 模块的 get_client_from_auth_file 方法初始化 ResourceManagementClient 和 ContainerInstanceManagementClient 对象。Once you've created the credentials file and populated the AZURE_AUTH_LOCATION environment variable, use the get_client_from_auth_file method of the client_factory module to initialize the ResourceManagementClient and ContainerInstanceManagementClient objects.

# Authenticate the management clients with Azure.
# Set the AZURE_AUTH_LOCATION environment variable to the full path to an
# auth file. Generate an auth file with the Azure CLI or Cloud Shell:
# az ad sp create-for-rbac --sdk-auth > my.azureauth
auth_file_path = getenv('AZURE_AUTH_LOCATION', None)
if auth_file_path is not None:
    print("Authenticating with Azure using credentials in file at {0}"
          .format(auth_file_path))

    aciclient = get_client_from_auth_file(
        ContainerInstanceManagementClient)
    resclient = get_client_from_auth_file(ResourceManagementClient)
else:
    print("\nFailed to authenticate to Azure. Have you set the"

若要更详细地了解用于 Azure 的 Python 管理库中提供的身份验证方法,请参阅使用用于 Python 的 Azure 管理库进行身份验证For more details about the available authentication methods in the Python management libraries for Azure, see Authenticate with the Azure Management Libraries for Python.

创建容器组 - 单个容器Create container group - single container

此示例创建包含单个容器的容器组This example creates a container group with a single container


def create_container_group(aci_client, resource_group,
                           container_group_name, container_image_name):
    """Creates a container group with a single container.

    Arguments:
        aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient}
                    -- An authenticated container instance management client.
        resource_group {azure.mgmt.resource.resources.models.ResourceGroup}
                    -- The resource group in which to create the container group.
        container_group_name {str}
                    -- The name of the container group to create.
        container_image_name {str}
                    -- The container image name and tag, for example:
                       microsoft\aci-helloworld:latest
    """
    print("Creating container group '{0}'...".format(container_group_name))

    # Configure the container
    container_resource_requests = ResourceRequests(memory_in_gb=1, cpu=1.0)
    container_resource_requirements = ResourceRequirements(
        requests=container_resource_requests)
    container = Container(name=container_group_name,
                          image=container_image_name,
                          resources=container_resource_requirements,
                          ports=[ContainerPort(port=80)])

    # Configure the container group
    ports = [Port(protocol=ContainerGroupNetworkProtocol.tcp, port=80)]
    group_ip_address = IpAddress(ports=ports,
                                 dns_name_label=container_group_name,
                                 type="Public")
    group = ContainerGroup(location=resource_group.location,
                           containers=[container],
                           os_type=OperatingSystemTypes.linux,
                           ip_address=group_ip_address)

    # Create the container group
    aci_client.container_groups.create_or_update(resource_group.name,
                                                 container_group_name,
                                                 group)

    # Get the created container group
    container_group = aci_client.container_groups.get(resource_group.name,
                                                      container_group_name)

    print("Once DNS has propagated, container group '{0}' will be reachable at"
          " http://{1}".format(container_group_name,

创建容器组 - 多个容器Create container group - multiple containers

此示例创建的容器组包含两个容器:应用程序容器和挎斗容器。This example creates a container group with two containers: an application container and a sidecar container.


def create_container_group_multi(aci_client, resource_group,
                                 container_group_name,
                                 container_image_1, container_image_2):
    """Creates a container group with two containers in the specified
       resource group.

    Arguments:
        aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient}
                    -- An authenticated container instance management client.
        resource_group {azure.mgmt.resource.resources.models.ResourceGroup}
                    -- The resource group in which to create the container group.
        container_group_name {str}
                    -- The name of the container group to create.
        container_image_1 {str}
                    -- The first container image name and tag, for example:
                       microsoft\aci-helloworld:latest
        container_image_2 {str}
                    -- The second container image name and tag, for example:
                       microsoft\aci-tutorial-sidecar:latest
    """
    print("Creating container group '{0}'...".format(container_group_name))

    # Configure the containers
    container_resource_requests = ResourceRequests(memory_in_gb=2, cpu=1.0)
    container_resource_requirements = ResourceRequirements(
        requests=container_resource_requests)

    container_1 = Container(name=container_group_name + '-1',
                            image=container_image_1,
                            resources=container_resource_requirements,
                            ports=[ContainerPort(port=80)])

    container_2 = Container(name=container_group_name + '-2',
                            image=container_image_2,
                            resources=container_resource_requirements)

    # Configure the container group
    ports = [Port(protocol=ContainerGroupNetworkProtocol.tcp, port=80)]
    group_ip_address = IpAddress(
        ports=ports, dns_name_label=container_group_name, type='Public')
    group = ContainerGroup(location=resource_group.location,
                           containers=[container_1, container_2],
                           os_type=OperatingSystemTypes.linux,
                           ip_address=group_ip_address)

    # Create the container group
    aci_client.container_groups.create_or_update(resource_group.name,
                                                 container_group_name, group)

    # Get the created container group
    container_group = aci_client.container_groups.get(resource_group.name,
                                                      container_group_name)

创建基于任务的容器组Create task-based container group

此示例创建的容器组包含单个基于任务的容器。This example creates a container group with a single task-based container. 此示例演示多项功能:This example demonstrates several features:

  • 命令行重写 - 指定自定义命令行,该命令行不同于在容器的 Dockerfile CMD 行中指定的命令行。Command line override - A custom command line, different from that which is specified in the container's Dockerfile CMD line, is specified. 使用命令行重写,可以指定在容器启动时执行的自定义命令行,重写植入到容器中的默认命令行。Command line override allows you to specify a custom command line to execute at container startup, overriding the default command line baked-in to the container. 若要在容器启动时执行多个命令,则适用以下规范:Regarding executing multiple commands at container startup, the following applies:

    如果要运行带有多个命令行参数的单个命令,例如 echo FOO BAR,必须以字符串列表的形式向容器command 属性提供这些参数。If you want to run a single command with several command-line arguments, for example echo FOO BAR, you must supply them as a string list to the command property of the Container. 例如:For example:

    command = ['echo', 'FOO', 'BAR']

    但是,如果要运行可能带有多个参数的多个命令,必须执行 shell,并将链接的命令作为参数传递。If, however, you want to run multiple commands with (potentially) multiple arguments, you must execute a shell and pass the chained commands as an argument. 例如,这样可以执行 echotail 命令:For example, this executes both an echo and a tail command:

    command = ['/bin/sh', '-c', 'echo FOO BAR && tail -f /dev/null']

  • 环境变量 - 为容器组中的容器指定两个环境变量。Environment variables - Two environment variables are specified for the container in the container group. 可以使用环境变量修改运行时的脚本或应用程序行为,或以其他方式向容器中运行的应用程序传递动态信息。Use environment variables to modify script or application behavior at runtime, or otherwise pass dynamic information to an application running in the container.

  • 重启策略 - 为容器配置的重启策略为“从不”,这适用于基于任务的容器,此类容器是在执行批处理作业的过程中执行的。Restart policy - The container is configured with a restart policy of "Never," useful for task-based containers that are executed as part of a batch job.

  • 使用 AzureOperationPoller 进行操作轮询 - 在调用 create 方法以后,会进行操作轮询以确定操作完成时间,并可获取容器组的日志。Operation polling with AzureOperationPoller - After the create method is invoked, the operation is polled to determine when it has completed and the container group's logs can be obtained.

                               container_group.ip_address.fqdn))


def run_task_based_container(aci_client, resource_group, container_group_name,
                             container_image_name, start_command_line=None):
    """Creates a container group with a single task-based container who's
       restart policy is 'Never'. If specified, the container runs a custom
       command line at startup.

    Arguments:
        aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient}
                    -- An authenticated container instance management client.
        resource_group {azure.mgmt.resource.resources.models.ResourceGroup}
                    -- The resource group in which to create the container group.
        container_group_name {str}
                    -- The name of the container group to create.
        container_image_name {str}
                    -- The container image name and tag, for example:
                       microsoft\aci-helloworld:latest
        start_command_line {str}
                    -- The command line that should be executed when the
                       container starts. This value can be None.
    """
    # If a start command wasn't specified, use a default
    if start_command_line is None:
        start_command_line = "python wordcount.py http://shakespeare.mit.edu/romeo_juliet/full.html"

    # Configure some environment variables in the container which the
    # wordcount.py or other script can read to modify its behavior.
    env_var_1 = EnvironmentVariable(name='NumWords', value='5')
    env_var_2 = EnvironmentVariable(name='MinLength', value='8')

    print("Creating container group '{0}' with start command '{1}'"
          .format(container_group_name, start_command_line))

    # Configure the container
    container_resource_requests = ResourceRequests(memory_in_gb=1, cpu=1.0)
    container_resource_requirements = ResourceRequirements(
        requests=container_resource_requests)
    container = Container(name=container_group_name,
                          image=container_image_name,
                          resources=container_resource_requirements,
                          command=start_command_line.split(),
                          environment_variables=[env_var_1, env_var_2])

    # Configure the container group
    group = ContainerGroup(location=resource_group.location,
                           containers=[container],
                           os_type=OperatingSystemTypes.linux,
                           restart_policy=ContainerGroupRestartPolicy.never)

    # Create the container group
    result = aci_client.container_groups.create_or_update(resource_group.name,
                                                          container_group_name,
                                                          group)

    # Wait for the container create operation to complete. The operation is
    # "done" when the container group provisioning state is one of:
    # Succeeded, Canceled, Failed
    while result.done() is False:
        sys.stdout.write('.')
        time.sleep(1)

    # Get the provisioning state of the container group.
    container_group = aci_client.container_groups.get(resource_group.name,
                                                      container_group_name)
    if str(container_group.provisioning_state).lower() == 'succeeded':
        print("\nCreation of container group '{}' succeeded."
              .format(container_group_name))
    else:
        print("\nCreation of container group '{}' failed. Provisioning state"
              "is: {}".format(container_group_name,
                              container_group.provisioning_state))

    # Get the logs for the container
    logs = aci_client.container.list_logs(resource_group.name,
                                          container_group_name,

列出容器组List container groups

此示例列出资源组中的容器组,然后列显其部分属性。This example lists the container groups in a resource group and then prints a few of their properties.

列出容器组时,每个返回的组的 instance_viewNoneWhen you list container groups,the instance_view of each returned group is None. 若要获取某个容器组中容器的详细信息,必须接着对该容器组执行 get 操作,此操作会返回该组,并且该组的 instance_view 属性已填充。To get the details of the containers within a container group, you must then get the container group, which returns the group with its instance_view property populated. 如需通过示例来了解如何在容器组的 instance_view 中循环访问该组的容器,请参阅下一部分:获取现有的容器组See the next section, Get an existing container group, for an example of iterating over a container group's containers in its instance_view.

    print("Logs for container '{0}':".format(container_group_name))
    print("{0}".format(logs.content))


def list_container_groups(aci_client, resource_group):
    """Lists the container groups in the specified resource group.

    Arguments:
       aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient}
                   -- An authenticated container instance management client.
       resource_group {azure.mgmt.resource.resources.models.ResourceGroup}
                   -- The resource group containing the container group(s).
    """
    print("Listing container groups in resource group '{0}'...".format(
        resource_group.name))

获取现有的容器组Get an existing container group

此示例获取资源组中的特定容器组,然后列显其部分属性(包括其容器)及属性值。This example gets a specific container group from a resource group, and then prints a few of its properties (including its containers) and their values.

get 操作会返回一个容器组,并且该组的 instance_view 已填充,这样就可以循环访问该组中的每个容器。The get operation returns a container group with its instance_view populated, which allows you to iterate over each container in the group. 只有 get 操作会填充容器组的 instance_vew 属性--列出订阅或资源组中的容器组不会填充实例视图,因为列出操作的开销可能很昂贵(例如,如果列出数百个容器组,而每个容器组又可能包含多个容器,则开销会很大)。Only the get operation populates the instance_vew property of the container group--listing the container groups in a subscription or resource group doesn't populate the instance view due to the potentially expensive nature of the operation (for example, when listing hundreds of container groups, each potentially containing multiple containers). 如前面的列出容器组部分所述,在 list 操作之后,接着必须对特定的容器组执行 get 操作,以便获取其容器实例详细信息。As mentioned previously in the List container groups section, after a list, you must subsequently get a specific container group to obtain its container instance details.

        resource_group.name)

    for container_group in container_groups:
        print("  {0}".format(container_group.name))


def print_container_group_details(aci_client, resource_group, container_group_name):
    """Gets the specified container group and then prints a few of its properties and their values.

    Arguments:
        aci_client {azure.mgmt.containerinstance.ContainerInstanceManagementClient}
                    -- An authenticated container instance management client.
        resource_group {azure.mgmt.resource.resources.models.ResourceGroup}
                    -- The name of the resource group containing the container
                       group.
        container_group_name {str}
                    -- The name of the container group whose details should be
                       printed.
    """
    print("Getting container group details for container group '{0}'..."
          .format(container_group_name))

    container_group = aci_client.container_groups.get(resource_group.name,
                                                      container_group_name)
    print("------------------------")
    print("Name:   {0}".format(container_group.name))
    print("State:  {0}".format(container_group.provisioning_state))
    print("FQDN:   {0}".format(container_group.ip_address.fqdn))
    print("IP:     {0}".format(container_group.ip_address.ip))
    print("Region: {0}".format(container_group.location))

删除容器组Delete a container group

此示例删除资源组中的多个容器组,以及该资源组本身。This example deletes several container groups from a resource group, as well as the resource group.


# Clean up resources
input("Press ENTER to delete all resources created by this sample: ")
aciclient.container_groups.delete(resource_group_name,
                                  container_group_name)
aciclient.container_groups.delete(resource_group_name,
                                  multi_container_group_name)
aciclient.container_groups.delete(resource_group_name,
                                  task_container_group_name)

后续步骤Next steps