Librerie di Istanze di Azure Container per PythonAzure Container Instances libraries for Python

Usare le librerie di Istanze di Container di Microsoft Azure per Python per creare e gestire Istanze di Azure Container.Use the Microsoft Azure Container Instances libraries for Python to create and manage Azure container instances. Per altre informazioni, vedere Panoramica di Istanze di Azure Container.Learn more by reading the Azure Container Instances overview.

API di gestioneManagement APIs

È possibile usare la libreria di gestione per creare e gestire Istanze di Azure Container in Azure.Use the management library to create and manage Azure container instances in Azure.

Installare il pacchetto di gestione tramite pip:Install the management package via pip:

pip install azure-mgmt-containerinstance

Codice sorgente di esempioExample source

Se si preferisce visualizzarli nel contesto, gli esempi di codice riportati di seguito sono disponibili nel repository GitHub seguente: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

Per autenticare i client SDK, come i client di Resource Manager e Istanze di Azure Container nell'esempio seguente, uno dei metodi più semplici è l'autenticazione basata su file.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. Con l'autenticazione basata su file vengono eseguite query sulla variabile di ambiente AZURE_AUTH_LOCATION per individuare il percorso di un file delle credenziali.File-based authentication queries the AZURE_AUTH_LOCATION environment variable for the path to a credentials file. Per usare l'autenticazione basata su file:To use file-based authentication:

  1. Creare un file delle credenziali con l'interfaccia della riga di comando di Azure o Cloud Shell:Create a credentials file with the Azure CLI or Cloud Shell:

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

    Se si usa Cloud Shell per generare il file delle credenziali, copiarne il contenuto in un file locale a cui l'applicazione Python può accedere.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. Impostare la variabile di ambiente AZURE_AUTH_LOCATION sul percorso completo del file delle credenziali generato.Set the AZURE_AUTH_LOCATION environment variable to the full path of the generated credentials file. Ad esempio, in Bash:For example (in Bash):

    export AZURE_AUTH_LOCATION=/home/yourusername/my.azureauth
    

Dopo aver creato il file delle credenziali e aver popolato la variabile di ambiente AZURE_AUTH_LOCATION, usare il metodo get_client_from_auth_file degli oggetti client_factory module to initialize the ResourceManagementClient e 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")

Per altri dettagli sui metodi di autenticazione disponibili nelle librerie di gestione Python per Azure, vedere Eseguire l'autenticazione con le librerie di gestione di Azure per 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.

Creare un gruppo di contenitori: singolo contenitoreCreate container group - single container

Questo esempio crea un gruppo di contenitori con un singolo contenitore.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))

Creare un gruppo di contenitori: più contenitoriCreate container group - multiple containers

Questo esempio crea un gruppo di contenitori con due contenitori: un contenitore di applicazioni e un contenitore collaterale.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))

Creare un gruppo di contenitori basato su attivitàCreate task-based container group

Questo esempio crea un gruppo di contenitori con un singolo contenitore basato su attività.This example creates a container group with a single task-based container. L'esempio illustra diverse funzionalità:This example demonstrates several features:

  • Override della riga di comando. Viene specificata una riga di comando personalizzata, diversa da quella specificata nella riga CMD del Dockerfile del contenitore.Command line override - A custom command line, different from that which is specified in the container's Dockerfile CMD line, is specified. L'override della riga di comando consente di specificare una riga di comando personalizzata da eseguire all'avvio del contenitore in sostituzione di quella predefinita incorporata nel contenitore.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. Per l'esecuzione di più comandi all'avvio del contenitore, si applica quanto segue:Regarding executing multiple commands at container startup, the following applies:

    Se si vuole eseguire un singolo comando con diversi argomenti della riga di comando, ad esempio echo FOO BAR, è necessario specificare gli argomenti come elenco di stringhe nella proprietà command del contenitore.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. Ad esempio:For example:

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

    Se invece si vogliono eseguire più comandi con (potenzialmente) più argomenti, è necessario eseguire una shell e passare i comandi concatenati come argomento.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. Questo codice, ad esempio, esegue i comandi echo e tail:For example, this executes both an echo and a tail command:

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

  • Variabili di ambiente. Per il contenitore nel gruppo di contenitori vengono specificate due variabili di ambiente.Environment variables - Two environment variables are specified for the container in the container group. Usare le variabili di ambiente per modificare il comportamento degli script o delle applicazioni in fase di esecuzione o in alternativa passare informazioni dinamiche a un'applicazione eseguita nel contenitore.Use environment variables to modify script or application behavior at runtime, or otherwise pass dynamic information to an application running in the container.

  • Criteri di riavvio. Il contenitore viene configurato con il criterio di riavvio "Mai", utile per i contenitori basati su attività eseguiti come parte di un processo batch.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.

  • Polling dell'operazione con AzureOperationPoller. Dopo la chiamata del metodo di creazione, viene eseguito il polling dell'operazione per determinare se è stata completata e se è possibile ottenere i log del gruppo di contenitori.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))

Elencare i gruppi di contenitoriList container groups

Questo esempio elenca i gruppi di contenitori in un gruppo di risorse e quindi stampa alcune proprietà.This example lists the container groups in a resource group and then prints a few of their properties.

Quando si elencano i gruppi di contenitori, il valore della proprietà instance_view di ogni gruppo restituito è None.When you list container groups,the instance_view of each returned group is None. Per ottenere i dettagli dei contenitori all'interno di un gruppo, è quindi necessario eseguire un'operazione get sul gruppo di contenitori, che restituirà il gruppo con la proprietà instance_view popolata.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. Per un esempio dell'iterazione sui contenitori di un gruppo in relazione alla proprietà instance_view, vedere la successiva sezione Ottenere un gruppo di contenitori esistente.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))

Ottenere un gruppo di contenitori esistenteGet an existing container group

Questo esempio ottiene un gruppo di contenitori specifico da un gruppo di risorse e quindi stampa alcune proprietà (inclusi i relativi contenitori) e i rispettivi valori.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.

L'operazione get returns a container group with its instance_view popolata, con cui è possibile eseguire l'iterazione su ogni contenitore del gruppo.The get operation returns a container group with its instance_view populated, which allows you to iterate over each container in the group. La proprietà instance_vew del gruppo di contenitori viene popolata solo dall'operazione get. Elencando i gruppi di contenitori in una sottoscrizione o in un gruppo di risorse non viene popolata la visualizzazione dell'istanza perché si tratta di un'operazione potenzialmente dispendiosa, ad esempio se l'elenco include centinaia di gruppi di contenitori in ognuno dei quali potrebbero essere presenti più contenitori.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). Come indicato in precedenza nella sezione Elencare i gruppi di contenitori, dopo un'operazione list è necessario eseguire un'operazione get su uno specifico gruppo di contenitori per ottenere i dettagli delle istanze di contenitore.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("  ----------")

Eliminare un gruppo di contenitoriDelete a container group

Questo esempio elimina diversi gruppi di contenitori da un gruppo di risorse, nonché il gruppo di risorse.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)

Passaggi successiviNext steps