Библиотеки службы "Экземпляры контейнеров Azure" для PythonAzure Container Instances libraries for Python

Создавайте и администрируйте экземпляры контейнеров Azure с помощью библиотеки службы "Экземпляры контейнеров Azure" для Python.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.

API управленияManagement APIs

Создавайте и администрируйте экземпляры контейнеров 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

АутентификацияAuthentication

Одним из самых простых способов аутентификации клиентских пакетов SDK (например, клиентов Resource Manager и службы "Экземпляры контейнеров 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 CLI или Cloud 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, используйте метод get_client_from_auth_file модуля client_factory для инициализации объектов module to initialize the 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_AUTH_LOCATION environment variable?\n")

Дополнительные сведения о доступных способах аутентификации в библиотеках управления Python для Azure см. в статье Проверка подлинности с помощью библиотек управления Azure для Python.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,
                               container_group.ip_address.fqdn))

Создание группы контейнеров с несколькими контейнерами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)

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

Создание группы контейнеров на основе задачCreate task-based container group

В этом примере создается группа контейнеров с одним контейнером на основе задач.This example creates a container group with a single task-based container. В этом примере показаны некоторые возможности:This example demonstrates several features:

  • Переопределение командной строки — задается пользовательская командная строка, отличная от указанной в строке CMD в файле Docker контейнера.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']

    Если нужно использовать несколько команд (возможно) с несколькими аргументами, выполните сценарий оболочки и передайте связанные команды в виде аргумента.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. Например, в этом случае выполняются команды echo и tail: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.

  • Политика перезапуска — в конфигурации контейнера для политики перезапуска задано значение "Never". Это полезно для контейнеров на основе задач, выполняемых в рамках пакетного задания.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 — после вызова метода создания выполняется опрос операции, чтобы определить время ее завершения и получить журналы группы.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.

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, 
                                          container.name)

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

Получение списка групп контейнеровList container groups

В этом примере выводится список групп контейнеров в группе ресурсов и некоторые свойства группы контейнеров.This example lists the container groups in a resource group and then prints a few of their properties.

При отображении списка групп контейнеров для свойства instance_view каждой возвращаемой группы задано значение None.When 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.

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))

    container_groups = aci_client.container_groups.list_by_resource_group(resource_group.name)

    for container_group in container_groups:
        print("  {0}".format(container_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 возвращает группу контейнеров с заполненным свойством returns a container group with its 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. Свойство instance_vew группы контейнеров заполняет только операция get. При получении списка групп контейнеров в подписке или группе ресурсов это свойство не заполняется, так как операция может повлечь большие затраты, например, при получении списка сотен групп контейнеров, каждая из которых может содержать несколько контейнеров.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.

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))
    print("Containers:")
    for container in container_group.containers:
        print("  Name:  {0}".format(container.name))
        print("  Image: {0}".format(container.image))
        print("  State: {0}".format(container.instance_view.current_state.state))
        print("  ----------")

Удаление группы контейнеров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)
resclient.resource_groups.delete(resource_group_name)

Дополнительная информацияNext steps