文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例。
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用 AWS SDKs Amazon ECS 程式碼範例
下列程式碼範例示範如何使用 Amazon Elastic Container Service 搭配 AWS 軟體開發套件 (SDK)。
Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境中查看內容中的動作。
案例是向您展示如何呼叫服務中的多個函數或與其他 AWS 服務組合來完成特定任務的程式碼範例。
開始使用
下列程式碼範例示範如何開始使用 Amazon ECS。
- .NET
-
- 適用於 .NET 的 SDK (v4)
-
using Amazon.ECS;
using Amazon.ECS.Model;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;
namespace ECSActions;
/// <summary>
/// A class that introduces the Amazon ECS Client by listing the
/// cluster ARNs for the account.
/// </summary>
public class HelloECS
{
static async System.Threading.Tasks.Task Main(string[] args)
{
// Use the AWS .NET Core Setup package to set up dependency injection for the Amazon ECS client.
// Use your AWS profile name, or leave it blank to use the default profile.
using var host = Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
logging.AddFilter("System", LogLevel.Debug)
.AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
.AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
.ConfigureServices((_, services) =>
services.AddAWSService<IAmazonECS>()
)
.Build();
var amazonECSClient = host.Services.GetRequiredService<IAmazonECS>();
Console.WriteLine($"Hello Amazon ECS! Following are some cluster ARNS available in the your account");
Console.WriteLine();
var clusters = new List<string>();
var clustersPaginator = amazonECSClient.Paginators.ListClusters(new ListClustersRequest());
await foreach (var response in clustersPaginator.Responses)
{
clusters.AddRange(response.ClusterArns);
}
if (clusters.Count > 0)
{
clusters.ForEach(cluster =>
{
Console.WriteLine($"\tARN: {cluster}");
Console.WriteLine($"Cluster Name: {cluster.Split("/").Last()}");
Console.WriteLine();
});
}
else
{
Console.WriteLine("No clusters were found.");
}
}
}