AWS SDK for .NET を使用したシンプルなクロスプラットフォームアプリケーション - AWS SDK for .NET

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

AWS SDK for .NET を使用したシンプルなクロスプラットフォームアプリケーション

このチュートリアルでは、AWS SDK for .NET と .NET Core を使用して、クロスプラットフォーム開発を行います。また、SDK を使用して、所有する Amazon S3 バケットを一覧表示し、必要に応じてバケットを作成する方法を説明します。

このチュートリアルは、.NET コマンドラインインターフェイス (CLI) などのクロスプラットフォームツールを使用して実行します。開発環境を設定するその他の方法については、「ツールチェーンのインストールと設定」を参照してください。

Windows、Linux、または macOS でのクロスプラットフォームの .NET 開発では必須:

  • Microsoft .NET Core SDK、バージョン 2.1、3.1 以降。.NET コマンドラインインターフェイス (CLI) (dotnet) および .NET Core ランタイムを含むものとします。

注記

これらのチュートリアルを使用する前に、まずツールチェーンをインストールし、SDK 認証を設定しておく必要があります。

ステップ

プロジェクトの作成

  1. コマンドプロントまたはターミナルを開きます。.NET プロジェクトを作成できるオペレーティングシステムフォルダを検索するか作成します。

  2. そのフォルダで、次のコマンドを実行して .NET プロジェクトを作成します。

    dotnet new console --name S3CreateAndList
  3. 新しく作成した S3CreateAndList フォルダに移動し、次のコマンドを実行します。

    dotnet add package AWSSDK.S3 dotnet add package AWSSDK.SecurityToken dotnet add package AWSSDK.SSO dotnet add package AWSSDK.SSOOIDC

    上記のコマンドは、NuGet パッケージ マネージャーから NuGet パッケージをインストールします。このチュートリアルに必要な NuGet パッケージは正確にわかっているため、ここでこのステップを実行できます。また、開発中に必要なパッケージが判明することは一般的なことです。その場合は、その時点で同様のコマンドを実行できます。

コードの作成

  1. S3CreateAndList フォルダで、Program.cs を見つけてコードエディタで開きます。

  2. 内容を次のコードに置き換えて、ファイルを保存します。

    using System; using System.Threading.Tasks; // NuGet packages: AWSSDK.S3, AWSSDK.SecurityToken, AWSSDK.SSO, AWSSDK.SSOOIDC using Amazon.Runtime; using Amazon.Runtime.CredentialManagement; using Amazon.S3; using Amazon.S3.Model; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; namespace S3CreateAndList { class Program { // This code is part of the quick tour in the developer guide. // See https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/quick-start.html // for complete steps. // Requirements: // - An SSO profile in the SSO user's shared config file with sufficient privileges for // STS and S3 buckets. // - An active SSO Token. // If an active SSO token isn't available, the SSO user should do the following: // In a terminal, the SSO user must call "aws sso login". // Class members. static async Task Main(string[] args) { // Get SSO credentials from the information in the shared config file. // For this tutorial, the information is in the [default] profile. var ssoCreds = LoadSsoCredentials("default"); // Display the caller's identity. var ssoProfileClient = new AmazonSecurityTokenServiceClient(ssoCreds); Console.WriteLine($"\nSSO Profile:\n {await ssoProfileClient.GetCallerIdentityArn()}"); // Create the S3 client is by using the SSO credentials obtained earlier. var s3Client = new AmazonS3Client(ssoCreds); // Parse the command line arguments for the bucket name. if (GetBucketName(args, out String bucketName)) { // If a bucket name was supplied, create the bucket. // Call the API method directly try { Console.WriteLine($"\nCreating bucket {bucketName}..."); var createResponse = await s3Client.PutBucketAsync(bucketName); Console.WriteLine($"Result: {createResponse.HttpStatusCode.ToString()}"); } catch (Exception e) { Console.WriteLine("Caught exception when creating a bucket:"); Console.WriteLine(e.Message); } } // Display a list of the account's S3 buckets. Console.WriteLine("\nGetting a list of your buckets..."); var listResponse = await s3Client.ListBucketsAsync(); Console.WriteLine($"Number of buckets: {listResponse.Buckets.Count}"); foreach (S3Bucket b in listResponse.Buckets) { Console.WriteLine(b.BucketName); } Console.WriteLine(); } // // Method to parse the command line. private static Boolean GetBucketName(string[] args, out String bucketName) { Boolean retval = false; bucketName = String.Empty; if (args.Length == 0) { Console.WriteLine("\nNo arguments specified. Will simply list your Amazon S3 buckets." + "\nIf you wish to create a bucket, supply a valid, globally unique bucket name."); bucketName = String.Empty; retval = false; } else if (args.Length == 1) { bucketName = args[0]; retval = true; } else { Console.WriteLine("\nToo many arguments specified." + "\n\ndotnet_tutorials - A utility to list your Amazon S3 buckets and optionally create a new one." + "\n\nUsage: S3CreateAndList [bucket_name]" + "\n - bucket_name: A valid, globally unique bucket name." + "\n - If bucket_name isn't supplied, this utility simply lists your buckets."); Environment.Exit(1); } return retval; } // // Method to get SSO credentials from the information in the shared config file. static AWSCredentials LoadSsoCredentials(string profile) { var chain = new CredentialProfileStoreChain(); if (!chain.TryGetAWSCredentials(profile, out var credentials)) throw new Exception($"Failed to find the {profile} profile"); return credentials; } } // Class to read the caller's identity. public static class Extensions { public static async Task<string> GetCallerIdentityArn(this IAmazonSecurityTokenService stsClient) { var response = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest()); return response.Arn; } } }

アプリケーションを実行する

  1. 以下のコマンドを実行します。

    dotnet run
  2. 出力を調べ、所有している Amazon S3 バケットの数 (存在する場合) とその名前を確認します。

  3. 新しい Amazon S3 バケットの名前を選択します。「dotnet-quicktour-s3-1-cross-」をベースとして使用し、GUID や名前などのような一意のものを追加します。「Amazon S3 ユーザーガイド」の「バケット命名規則」で説明されているように、バケット名のルールに従ってください。

  4. 次のコマンドを実行し、BUCKET-NAME を、選択したバケットの名前に置き換えます。

    dotnet run BUCKET-NAME
  5. 出力を調べて、作成された新しいバケットを確認します。

クリーンアップ

このチュートリアルでは、この時点でクリーンアップを選択できるいくつかのリソースを作成しました。

  • 前のステップでアプリケーションが作成したバケットを保持しない場合は、https://console.aws.amazon.com/s3/ の Amazon S3 コンソールを使用してバケットを削除します。

  • .NET プロジェクトを保持しない場合は、開発環境から S3CreateAndList フォルダを削除します。

次の段階

クイックツアーメニューに戻るか、このクイックツアーの最後までスキップします。