Python용 Azure Container Instances 라이브러리Azure Container Instances libraries for Python

Python용 Microsoft Azure Container Instances 라이브러리를 사용하여 Azure Container Instances를 만들고 관리합니다.Use the Microsoft Azure Container Instances libraries for Python to create and manage Azure container instances. 자세한 내용은 Azure Container Instances 개요를 참조하세요.Learn more by reading the Azure Container Instances overview.

관리 APIManagement APIs

Azure에서 관리 라이브러리를 사용하여 Azure Container Instances를 만들고 관리합니다.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 클라이언트(예: 다음 예제의 Azure Container Instance 및 Resource Manager 클라이언트를 인증하는 가장 쉬운 방법)은 파일 기반 인증입니다.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 환경 변수를 채웠다면, client_factory module to initialize the ResourceManagementClientContainerInstanceManagementClient 개체의 get_client_from_auth_file 메서드를 사용합니다.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 관리 라이브러리에 사용가능한 인증 방법에 대한 자세한 내용은 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,
                               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:

  • 명령줄 재정의 - 컨테이너의 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']

    그러나 (잠재적으로) 여러 인수를 사용하여 여러 명령을 실행하려는 경우, 셸을 실행하고 연결된 명령을 인수로서 전달해야 합니다.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.

  • 정책 다시 시작 - 해당 컨테이너는 "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로 폴링하여 작업 - 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.

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_viewNone입니다.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.

가져오기 작업 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. 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.

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