.NET 用 Azure Container Instances ライブラリ
.NET 用 Microsoft Azure Container Instances ライブラリを使用して、Azure コンテナー インスタンスを作成し、管理します。 詳細については、Azure Container Instances の概要に関するページをご覧ください。
管理ライブラリ
管理ライブラリを使用して、Azure で Azure コンテナー インスタンスを作成して管理します。
NuGet パッケージを Visual Studio パッケージ マネージャー コンソールから直接インストールするか、.NET Core CLI を使ってインストールします。
Visual Studio パッケージ マネージャー
Install-Package Microsoft.Azure.Management.ContainerInstance.Fluent
dotnet add package Microsoft.Azure.Management.ContainerInstance.Fluent
サンプル ソース
以下のコード例をコンテキスト内で確認するには、次の GitHub リポジトリでサンプルを検索してください。
Azure-Samples/aci-docs-sample-dotnet
認証
SDK クライアントを認証する最も簡単な方法の 1 つは、ファイル ベースの認証を使う方法です。 ファイル ベースの認証では、IAzure クライアント オブジェクトのインスタンス化時に資格情報ファイルが解析され、Azure での認証時にこれらの資格情報がオブジェクトによって使用されます。 ファイル ベースの認証を使用するには:
Azure CLI または Cloud Shell で資格情報ファイルを作成します。
az ad sp create-for-rbac --sdk-auth > my.azureauth
Cloud Shell を使用して資格情報ファイルを生成する場合は、その内容を、お使いの .NET アプリケーションがアクセスできるローカル ファイルにコピーします。
AZURE_AUTH_LOCATION
環境変数を、生成された資格情報ファイルの完全なパスに設定します。 次に例を示します (Bash シェルの場合)。export AZURE_AUTH_LOCATION=/home/yourusername/my.azureauth
資格情報ファイルを作成し、AZURE_AUTH_LOCATION
環境変数を設定したら、Azure.Authenticate メソッドを使用して、IAzure クライアント オブジェクトを初期化します。 例のプロジェクトでは、まず AZURE_AUTH_LOCATION
値を取得し、次に、初期化された IAzure
クライアント オブジェクト返すメソッドを呼び出します。
// 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);
サンプル アプリケーションのこのメソッドによって、初期化されたIAzure インスタンスが返され、次にこのインスタンスは最初のパラメーターとしてサンプルの他のすべてのメソッドに渡されます。
/// <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;
}
Azure の .NET 管理ライブラリで使用できる認証方法の詳細については、「Authentication in Azure Management Libraries for .NET (.NET 用 Azure 管理ライブラリを使用した認証)」を参照してください。
コンテナー グループを作成する - 1 つのコンテナー
この例では、1 つのコンテナーを含むコンテナー グループが作成されます。
/// <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}");
}
コンテナー グループを作成する - 複数のコンテナー
この例では、アプリケーション コンテナーとサイドカー コンテナーという 2 つのコンテナーを含むコンテナー グループが作成されます。
/// <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}");
}
ポーリングを使用して非同期でコンテナーを作成する
この例では、1 つのコンテナーを含むコンテナー グループを非同期で作成されます。 その後、コンテナー グループについて Azure にポーリングが実行され、状態が "実行中" になるまでコンテナー グループの状態が出力されます。
/// <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}");
}
タスク ベースのコンテナー グループを作成する
この例では、1 つのタスク ベースのコンテナーを含むコンテナー グループが作成されます。 コンテナーは、再起動ポリシー "Never" とカスタム コマンド ラインで構成されます。
echo FOO BAR
など、1 つのコマンドを、複数のコマンド ライン引数を指定して実行する場合、その引数は、1 つの文字列の配列として WithStartingCommandLines
メソッドに指定する必要があります。 次に例を示します。
WithStartingCommandLines("echo", "FOO", "BAR")
ただし、複数のコマンドを、複数の (可能性がある) 引数を指定して実行する場合は、シェルを実行し、チェーンされたコマンドを 1 つの引数として渡す必要があります。 たとえば、これにより echo
と tail
コマンドの両方が実行されます。
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"));
}
コンテナー グループの一覧を表示する
この例では、リソース グループ内のコンテナー グループの一覧が表示されます。
/// <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}");
}
}
既存のコンテナー グループを取得する
この例では、リソース グループ内に存在する特定のコンテナー グループが取得され、そのプロパティとその値がいくつか出力されます。
/// <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}");
}
コンテナー グループを削除する
この例では、リソース グループからコンテナー グループが削除されます。
/// <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 リファレンス
サンプル
前の例のソース コードは GitHub で確認できます。
Azure Container Instances のその他のコード サンプル:
アプリで使用できるその他のサンプル .NET コードを確認してください。
Azure SDK for .NET
フィードバック
https://aka.ms/ContentUserFeedback」を参照してください。
以下は間もなく提供いたします。2024 年を通じて、コンテンツのフィードバック メカニズムとして GitHub の issue を段階的に廃止し、新しいフィードバック システムに置き換えます。 詳細については、「フィードバックの送信と表示