Librerie di Istanze di Azure Container per .NETAzure Container Instances libraries for .NET

È possibile usare le librerie di Istanze di Container di Microsoft Azure per .NET per creare e gestire Istanze di Azure Container.Use the Microsoft Azure Container Instances libraries for .NET 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.

Libreria di gestioneManagement library

È 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 NuGet direttamente dalla Console di Gestione pacchetti di Visual Studio o tramite l'interfaccia della riga di comando di .NET Core.Install the NuGet package directly from the Visual Studio Package Manager console or with the .NET Core CLI.

Visual Studio - Gestione pacchettiVisual Studio Package Manager

Install-Package Microsoft.Azure.Management.ContainerInstance.Fluent
dotnet add package Microsoft.Azure.Management.ContainerInstance.Fluent

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-dotnetAzure-Samples/aci-docs-sample-dotnet

AuthenticationAuthentication

Uno dei modi più semplici per autenticare i client SDK è l'autenticazione basata su file.One of the easiest ways to authenticate SDK clients is with file-based authentication. L'autenticazione basata su file analizza un file di credenziali quando si creano istanze dell'oggetto client IAzure, che quindi usa tali credenziali per l'autenticazione con Azure.File-based authentication parses a credentials file when instantiating the IAzure client object, which then uses those credentials when authenticating with Azure. 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 .NET può accedere.If you use the Cloud Shell to generate the credentials file, copy its contents into a local file that your .NET 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 (nella shell di Bash):For example (in the Bash shell):

    export AZURE_AUTH_LOCATION=/home/yourusername/my.azureauth
    

Dopo aver creato il file delle credenziali e popolato la variabile di ambiente AZURE_AUTH_LOCATION, usare il metodo Azure.Authenticate per inizializzare l'oggetto client IAzure.Once you've created the credentials file and populated the AZURE_AUTH_LOCATION environment variable, use the Azure.Authenticate method to initialize the IAzure client object. Il progetto di esempio ottiene prima il valore AZURE_AUTH_LOCATION, quindi chiama un metodo che restituisce un oggetto client IAzure inizializzato:The example project first obtains the AZURE_AUTH_LOCATION value, then calls a method that returns an initialized IAzure client object:

// Set the AZURE_AUTH_LOCATION environment variable with the full
// path to an auth file. Create an auth file with the Azure CLI:
// az ad sp create-for-rbac --sdk-auth > my.azureauth
string authFilePath = Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION");

// Authenticate with Azure
IAzure azure = GetAzureContext(authFilePath);

Questo metodo dell'applicazione di esempio restituisce l'istanza di IAzure inizializzata, che viene quindi passata come primo parametro a tutti gli altri metodi dell'esempio:This method from the sample application returns the initialized IAzure instance, which is then passed as the first parameter to all other methods in the sample:

/// <summary>
/// Returns an authenticated Azure context using the credentials in the
/// specified auth file.
/// </summary>
/// <param name="authFilePath">The full path to a credentials file on the local filesystem.</param>
/// <returns>Authenticated IAzure context.</returns>
private static IAzure GetAzureContext(string authFilePath)
{            
    IAzure azure;
    ISubscription sub;

    try
    {
        Console.WriteLine($"Authenticating with Azure using credentials in file at {authFilePath}");

        azure = Azure.Authenticate(authFilePath).WithDefaultSubscription();
        sub = azure.GetCurrentSubscription();

        Console.WriteLine($"Authenticated with subscription '{sub.DisplayName}' (ID: {sub.SubscriptionId})");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"\nFailed to authenticate:\n{ex.Message}");

        if (String.IsNullOrEmpty(authFilePath))
        {
            Console.WriteLine("Have you set the AZURE_AUTH_LOCATION environment variable?");
        }

        throw;
    }

    return azure;
}

Per altri dettagli sui metodi di autenticazione disponibili nelle librerie di gestione .NET per Azure, vedere Authentication in Azure Management Libraries for .NET (Eseguire l'autenticazione con le librerie di gestione di Azure per .NET).For more details about the available authentication methods in the .NET management libraries for Azure, see Authentication in Azure Management Libraries for .NET.

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.

/// <summary>
/// Creates a container group with a single container.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage">The container image name and tag, for example 'microsoft\aci-helloworld:latest'.</param>
private static void CreateContainerGroup(IAzure azure,
                                         string resourceGroupName, 
                                         string containerGroupName, 
                                         string containerImage)
{
    Console.WriteLine($"\nCreating container group '{containerGroupName}'...");

    // Get the resource group's region
    IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
    Region azureRegion = resGroup.Region;

    // Create the container group
    var containerGroup = azure.ContainerGroups.Define(containerGroupName)
        .WithRegion(azureRegion)
        .WithExistingResourceGroup(resourceGroupName)
        .WithLinux()
        .WithPublicImageRegistryOnly()
        .WithoutVolume()
        .DefineContainerInstance(containerGroupName + "-1")
            .WithImage(containerImage)
            .WithExternalTcpPort(80)
            .WithCpuCoreCount(1.0)
            .WithMemorySizeInGB(1)
            .Attach()
        .WithDnsPrefix(containerGroupName)
        .Create();

    Console.WriteLine($"Once DNS has propagated, container group '{containerGroup.Name}' will be reachable at http://{containerGroup.Fqdn}");
}

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

Questo esempio crea un gruppo di contenitori con due contenitori, ovvero un contenitore di applicazioni e un contenitore collaterale.This example creates a container group with two containers: an application container and a sidecar container.

/// <summary>
/// Creates a container group with two containers in the specified resource group.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage1">The first container image name and tag, for example 'microsoft\aci-helloworld:latest'.</param>
/// <param name="containerImage2">The second container image name and tag, for example 'microsoft\aci-tutorial-sidecar:latest'.</param>
private static void CreateContainerGroupMulti(IAzure azure,
                                              string resourceGroupName,
                                              string containerGroupName, 
                                              string containerImage1, 
                                              string containerImage2)
{
    Console.WriteLine($"\nCreating multi-container container group '{containerGroupName}'...");

    // Get the resource group's region
    IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
    Region azureRegion = resGroup.Region;

    // Create the container group
    var containerGroup = azure.ContainerGroups.Define(containerGroupName)
        .WithRegion(azureRegion)
        .WithExistingResourceGroup(resourceGroupName)
        .WithLinux()
        .WithPublicImageRegistryOnly()
        .WithoutVolume()
        .DefineContainerInstance(containerGroupName + "-1")
            .WithImage(containerImage1)
            .WithExternalTcpPort(80)
            .WithCpuCoreCount(0.5)
            .WithMemorySizeInGB(1)
            .Attach()
        .DefineContainerInstance(containerGroupName + "-2")
            .WithImage(containerImage2)
            .WithoutPorts()
            .WithCpuCoreCount(0.5)
            .WithMemorySizeInGB(1)
            .Attach()
        .WithDnsPrefix(containerGroupName)
        .Create();

    Console.WriteLine($"Once DNS has propagated, container group '{containerGroup.Name}' will be reachable at http://{containerGroup.Fqdn}");
}

Creazione asincrona di contenitori con pollingAsynchronous container create with polling

Questo esempio crea un gruppo di contenitori con un singolo contenitore usando il metodo di creazione asincrona.This example creates a container group with a single container using the async create method. Viene quindi eseguito il polling di Azure per il gruppo di contenitori e viene restituito lo stato del gruppo di contenitori fino a lo stato non è "In esecuzione".It then polls Azure for the container group, and outputs the container group's status until its state is "Running."

/// <summary>
/// Creates a container group with a single container asynchronously, and
/// polls its status until its state is 'Running'.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage">The container image name and tag, for example 'microsoft\aci-helloworld:latest'.</param>
private static void CreateContainerGroupWithPolling(IAzure azure,
                                         string resourceGroupName, 
                                         string containerGroupName, 
                                         string containerImage)
{
    Console.WriteLine($"\nCreating container group '{containerGroupName}'...");

    // Get the resource group's region
    IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
    Region azureRegion = resGroup.Region;

    // Create the container group using a fire-and-forget task
    Task.Run(() =>

        azure.ContainerGroups.Define(containerGroupName)
            .WithRegion(azureRegion)
            .WithExistingResourceGroup(resourceGroupName)
            .WithLinux()
            .WithPublicImageRegistryOnly()
            .WithoutVolume()
            .DefineContainerInstance(containerGroupName + "-1")
                .WithImage(containerImage)
                .WithExternalTcpPort(80)
                .WithCpuCoreCount(1.0)
                .WithMemorySizeInGB(1)
                .Attach()
            .WithDnsPrefix(containerGroupName)
            .CreateAsync()
    );

    // Poll for the container group
    IContainerGroup containerGroup = null;
    while(containerGroup == null)
    {
        containerGroup = azure.ContainerGroups.GetByResourceGroup(resourceGroupName, containerGroupName);

        Console.Write(".");

        SdkContext.DelayProvider.Delay(1000);
    }

    Console.WriteLine();

    // Poll until the container group is running
    while(containerGroup.State != "Running")
    {
        Console.WriteLine($"Container group state: {containerGroup.Refresh().State}");
        
        Thread.Sleep(1000);
    }

    Console.WriteLine($"\nOnce DNS has propagated, container group '{containerGroup.Name}' will be reachable at http://{containerGroup.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. Il contenitore viene configurato con un criterio di riavvio impostato su "Mai" e una riga di comando personalizzata.The container is configured with a restart policy of "Never" and a custom command line.

Se si vuole eseguire un singolo comando con diversi argomenti della riga di comando, ad esempio echo FOO BAR, è necessario fornirli come matrice di stringa al metodo WithStartingCommandLines.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 array to the WithStartingCommandLines method. Ad esempio: For example:

WithStartingCommandLines("echo", "FOO", "BAR")

Se tuttavia 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. Il codice seguente, ad esempio, esegue i comandi echo e tail:For example, this executes both an echo and a tail command:

WithStartingCommandLines("/bin/sh", "-c", "echo FOO BAR && tail -f /dev/null")

/// <summary>
/// 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.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group in which to create the container group.</param>
/// <param name="containerGroupName">The name of the container group to create.</param>
/// <param name="containerImage">The container image name and tag, for example 'microsoft\aci-wordcount:latest'.</param>
/// <param name="startCommandLine">The command line that should be executed when the container starts. This value can be <c>null</c>.</param>
private static void RunTaskBasedContainer(IAzure azure,
                                         string resourceGroupName, 
                                         string containerGroupName, 
                                         string containerImage,
                                         string startCommandLine)
{
    // If a start command wasn't specified, use a default
    if (String.IsNullOrEmpty(startCommandLine))
    {
        startCommandLine = "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.
    Dictionary<string, string> envVars = new Dictionary<string, string>
    {
        { "NumWords", "5" },
        { "MinLength", "8" }
    };

    Console.WriteLine($"\nCreating container group '{containerGroupName}' with start command '{startCommandLine}'");

    // Get the resource group's region
    IResourceGroup resGroup = azure.ResourceGroups.GetByName(resourceGroupName);
    Region azureRegion = resGroup.Region;

    // Create the container group
    var containerGroup = azure.ContainerGroups.Define(containerGroupName)
        .WithRegion(azureRegion)
        .WithExistingResourceGroup(resourceGroupName)
        .WithLinux()
        .WithPublicImageRegistryOnly()
        .WithoutVolume()
        .DefineContainerInstance(containerGroupName + "-1")
            .WithImage(containerImage)
            .WithExternalTcpPort(80)
            .WithCpuCoreCount(1.0)
            .WithMemorySizeInGB(1)
            .WithStartingCommandLines(startCommandLine.Split())
            .WithEnvironmentVariables(envVars)
            .Attach()
        .WithDnsPrefix(containerGroupName)
        .WithRestartPolicy(ContainerGroupRestartPolicy.Never)
        .Create();

    // Print the container's logs
    Console.WriteLine($"Logs for container '{containerGroupName}-1':");
    Console.WriteLine(containerGroup.GetLogContent(containerGroupName + "-1"));
}

Elencare gruppi di contenitoriList container groups

Questo esempio elenca i gruppi di contenitori in un gruppo di risorse.This example lists the container groups in a resource group.

/// <summary>
/// Prints the container groups in the specified resource group.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group containing the container group(s).</param>
private static void ListContainerGroups(IAzure azure, string resourceGroupName)
{
    Console.WriteLine($"Listing container groups in resource group '{resourceGroupName}'...");

    foreach (var containerGroup in azure.ContainerGroups.ListByResourceGroup(resourceGroupName))
    {
        Console.WriteLine($"{containerGroup.Name}");
    }
}

Ottenere un gruppo di contenitori esistenteGet an existing container group

Questo esempio ottiene un gruppo di contenitori specifico che si trova in un gruppo di risorse e quindi stampa alcune proprietà e i rispettivi valori.This example gets a specific container group residing in a resource group and then prints a few of its properties and their values.

/// <summary>
/// Gets the specified container group and then prints a few of its properties and their values.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group containing the container group.</param>
/// <param name="containerGroupName">The name of the container group whose details should be printed.</param>
private static void PrintContainerGroupDetails(IAzure azure, string resourceGroupName, string containerGroupName)
{
    Console.Write($"\nGetting container group details for container group '{containerGroupName}'...");

    IContainerGroup containerGroup = null;
    while (containerGroup == null)
    {
        Console.Write(".");

        containerGroup = azure.ContainerGroups.GetByResourceGroup(resourceGroupName, containerGroupName);

        SdkContext.DelayProvider.Delay(1000);
    }

    Console.WriteLine();
    Console.WriteLine(containerGroup.Name);
    Console.WriteLine("--------------------------------");
    Console.WriteLine($"State:  {containerGroup.State}");
    Console.WriteLine($"FQDN:   {containerGroup.Fqdn}");
    Console.WriteLine($"IP:     {containerGroup.IPAddress}");
    Console.WriteLine($"Region: {containerGroup.RegionName}");
}

Eliminare un gruppo di contenitoriDelete a container group

Questo esempio elimina un gruppo di contenitori da un gruppo di risorse.This example deletes a container group from a resource group.

/// <summary>
/// Deletes the specified container group.
/// </summary>
/// <param name="azure">An authenticated IAzure object.</param>
/// <param name="resourceGroupName">The name of the resource group containing the container group.</param>
/// <param name="containerGroupName">The name of the container group to delete.</param>
private static void DeleteContainerGroup(IAzure azure, string resourceGroupName, string containerGroupName)
{
    IContainerGroup containerGroup = null;

    while (containerGroup == null)
    {
        containerGroup = azure.ContainerGroups.GetByResourceGroup(resourceGroupName, containerGroupName);

        SdkContext.DelayProvider.Delay(1000);
    }

    Console.WriteLine($"Deleting container group '{containerGroupName}'...");

    azure.ContainerGroups.DeleteById(containerGroup.Id);
}

Informazioni di riferimento sulle APIAPI reference

EsempiSamples

Esplorare altro codice .NET di esempio da usare nelle app.Explore more sample .NET code you can use in your apps.