Azure Container Instances libraries for .NET

Use the Microsoft Azure Container Instances libraries for .NET to create and manage Azure container instances. Learn more by reading the Azure Container Instances overview.

Management library

Use the management library to create and manage Azure container instances in Azure.

Install the NuGet package directly from the Visual Studio Package Manager console or with the .NET Core CLI.

Visual Studio Package Manager

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

Example source

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

Authentication

One of the easiest ways to authenticate SDK clients is with file-based authentication. File-based authentication parses a credentials file when instantiating the IAzure client object, which then uses those credentials when authenticating with Azure. To use file-based authentication:

  1. Create a credentials file with the Azure CLI or Cloud Shell:

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

    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. Set the AZURE_AUTH_LOCATION environment variable to the full path of the generated credentials file. For example (in the Bash shell):

    export AZURE_AUTH_LOCATION=/home/yourusername/my.azureauth
    

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

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;
}

For more details about the available authentication methods in the .NET management libraries for Azure, see Authentication in Azure Management Libraries for .NET.

Create container group - single container

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}");
}

Create container group - multiple containers

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}");
}

Asynchronous container create with polling

This example creates a container group with a single container using the async create method. 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}");
}

Create task-based container group

This example creates a container group with a single task-based container. The container is configured with a restart policy of "Never" and a custom command line.

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. For example:

WithStartingCommandLines("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. 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"));
}

List container groups

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}");
    }
}

Get an existing container group

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}");
}

Delete a container group

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

API reference

Samples

Explore more sample .NET code you can use in your apps.