IAM ロールを使用したアクセス権の付与 - AWS SDK for .NET

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

IAM ロールを使用したアクセス権の付与

このチュートリアルでは、 を使用して Amazon EC2 インスタンスで IAM ロール AWS SDK for .NET を有効にする方法を示します。

概要

へのすべてのリクエストは、 によって発行された認証情報を使用して暗号で署名 AWS する必要があります AWS。したがって、Amazon EC2 インスタンスで実行するアプリケーション用の認証情報を管理するための戦略が必要です。これらの認証情報を、アプリケーションからのアクセスを維持したまま安全に配信、保存、ローテーションする必要があります。

IAM ロールを使用すると、認証情報を効果的に管理できます。IAM ロールを作成し、アプリケーションに必要なアクセス許可を使用して設定を行った後で、そのロールを EC2 インスタンスにアタッチします。IAM ロールを使用する利点の詳細については、Linux インスタンス用の Amazon EC2 ユーザーガイドまたは Windows インスタンス用の Amazon EC2 ユーザーガイドを参照してください。また、IAM ユーザーガイドの「IAM ロール」の情報も参照してください。

を使用して構築されたアプリケーションの場合 AWS SDK for .NET、アプリケーションが AWS サービスのクライアントオブジェクトを構築すると、オブジェクトはいくつかの潜在的なソースから認証情報を検索します。検索の順序は、「認証情報とプロファイルの解決」に示されています。

クライアントオブジェクトが他のソースから認証情報を見つけられなかった場合、クライアントオブジェクトは IAM ロールに設定された、EC2 インスタンスのメタデータにあるものと同じアクセス許可を持つ一時的な認証情報を取得します。これらの認証情報は、クライアントオブジェクト AWS から を呼び出すために使用されます。

このチュートリアルの内容

このチュートリアルでは、 AWS SDK for .NET (およびその他のツール) を使用して IAM ロールがアタッチされた Amazon EC2 インスタンスを起動し、IAM ロールのアクセス許可を使用してインスタンス上のアプリケーションを確認します。

サンプルの Amazon S3 アプリケーションの作成

このサンプルアプリケーションは、Amazon S3 からオブジェクトを取得します。アプリケーションを実行するには、以下が必要です。

  • テキストファイルを含む Amazon S3 バケット。

  • AWS バケットへのアクセスを許可する開発マシン上の 認証情報。

Amazon S3 バケットの作成およびオブジェクトのアップロードの詳細については、「Amazon Simple Storage Service ユーザーガイド」を参照してください。 AWS 認証情報の詳細については、「」を参照してくださいAWSで SDK 認証を設定します

以下のコードを使用して、.NET Core プロジェクトを作成します。次に、開発マシンでアプリケーションをテストします。

注記

開発マシンには .NET Core Runtime がインストールされており、アプリケーションを公開しなくても実行できます。このチュートリアルの後半で EC2 インスタンスを作成するときに、インスタンスに .NET Core Runtime をインストールすることができます。こうすることで同様のエクスペリエンスを実現でき、ファイル転送量が小さくなります。

ただし、インスタンスに .NET Core Runtime をインストールしない選択も可能です。この場合は、インスタンスを転送するときにすべての依存関係が含まれるようにアプリケーションを公開する必要があります。

NuGet パッケージ:

プログラミング要素:

using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; namespace S3GetTextItem { // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class to retrieve a text file from an S3 bucket and write it to a local file class Program { static async Task Main(string[] args) { // Parse the command line and show help if necessary var parsedArgs = CommandLine.Parse(args); if(parsedArgs.Count == 0) { PrintHelp(); return; } // Get the application arguments from the parsed list string bucket = CommandLine.GetArgument(parsedArgs, null, "-b", "--bucket-name"); string item = CommandLine.GetArgument(parsedArgs, null, "-t", "--text-object"); string outFile = CommandLine.GetArgument(parsedArgs, null, "-o", "--output-filename"); if( string.IsNullOrEmpty(bucket) || string.IsNullOrEmpty(item) || string.IsNullOrEmpty(outFile)) CommandLine.ErrorExit( "\nOne or more of the required arguments is missing or incorrect." + "\nRun the command with no arguments to see help."); // Create the S3 client object and get the file object from the bucket. var response = await GetObject(new AmazonS3Client(), bucket, item); // Write the contents of the file object to the given output file. var reader = new StreamReader(response.ResponseStream); string contents = reader.ReadToEnd(); using (var s = new FileStream(outFile, FileMode.Create)) using (var writer = new StreamWriter(s)) writer.WriteLine(contents); } // // Method to get an object from an S3 bucket. private static async Task<GetObjectResponse> GetObject( IAmazonS3 s3Client, string bucket, string item) { Console.WriteLine($"Retrieving {item} from bucket {bucket}."); return await s3Client.GetObjectAsync(bucket, item); } // // Command-line help private static void PrintHelp() { Console.WriteLine( "\nUsage: S3GetTextItem -b <bucket-name> -t <text-object> -o <output-filename>" + "\n -b, --bucket-name: The name of the S3 bucket." + "\n -t, --text-object: The name of the text object in the bucket." + "\n -o, --output-filename: The name of the file to write the text to."); } } // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class that represents a command line on the console or terminal. // (This is the same for all examples. When you have seen it once, you can ignore it.) static class CommandLine { // // Method to parse a command line of the form: "--key value" or "-k value". // // Parameters: // - args: The command-line arguments passed into the application by the system. // // Returns: // A Dictionary with string Keys and Values. // // If a key is found without a matching value, Dictionary.Value is set to the key // (including the dashes). // If a value is found without a matching key, Dictionary.Key is set to "--NoKeyN", // where "N" represents sequential numbers. public static Dictionary<string,string> Parse(string[] args) { var parsedArgs = new Dictionary<string,string>(); int i = 0, n = 0; while(i < args.Length) { // If the first argument in this iteration starts with a dash it's an option. if(args[i].StartsWith("-")) { var key = args[i++]; var value = key; // Check to see if there's a value that goes with this option? if((i < args.Length) && (!args[i].StartsWith("-"))) value = args[i++]; parsedArgs.Add(key, value); } // If the first argument in this iteration doesn't start with a dash, it's a value else { parsedArgs.Add("--NoKey" + n.ToString(), args[i++]); n++; } } return parsedArgs; } // // Method to get an argument from the parsed command-line arguments // // Parameters: // - parsedArgs: The Dictionary object returned from the Parse() method (shown above). // - defaultValue: The default string to return if the specified key isn't in parsedArgs. // - keys: An array of keys to look for in parsedArgs. public static string GetArgument( Dictionary<string,string> parsedArgs, string defaultReturn, params string[] keys) { string retval = null; foreach(var key in keys) if(parsedArgs.TryGetValue(key, out retval)) break; return retval ?? defaultReturn; } // // Method to exit the application with an error. public static void ErrorExit(string msg, int code=1) { Console.WriteLine("\nError"); Console.WriteLine(msg); Environment.Exit(code); } } }

必要に応じて、開発マシンで使用している認証情報を一時的に削除して、アプリケーションの応答を確認できます。(ただし、完了したら認証情報を忘れずに復元してください)

IAM ロールの作成

Amazon S3 にアクセスするための適切なアクセス許可を持つ IAM ロールを作成します。

  1. [IAM コンソール] を開きます。

  2. ナビゲーションペインで [Roles] (ロール) を選択し、続いて [Create Role] (ロールの作成) を選択します。

  3. [AWS service] (AWS サービス) を選択し、[EC2] を見つけて選択して、[Next: Permissions] (次へ: アクセス許可) を選択します。

  4. 「アクセス許可ポリシーをアタッチする」で、AmazonS3ReadOnlyAccess を見つけて選択します。必要に応じてポリシーを確認し、[Next: Tags] (次へ: タグ) を選択します。

  5. 必要に応じてタグを追加し、[Next: Review] (次へ: レビュー) を選択します。

  6. ロールの名前と説明を入力し、[Create role] (ロールの作成) を選択します。この名前は EC2 インスタンスを起動するときに必要になるため、忘れないでください。

EC2 インスタンスの起動と IAM ロールのアタッチ

先ほど作成した IAM ロールを使用して EC2 インスタンスを起動します。これは以下の方法で実行できます。

IAM ロールが添付された EC2 インスタンスを起動するには、IAM ユーザーの設定に特定のアクセス許可が含まれている必要があります。必要な権限の詳細については、Linux インスタンス用 Amazon EC2 ユーザーガイドまたは Windows インスタンス用 Amazon EC2 ユーザーガイドを参照してください。

EC2 インスタンスへの接続

EC2 インスタンスに接続することで、サンプルアプリケーションをそのインスタンスに転送して、アプリケーションを実行できるようにします。また、インスタンスの起動に使用したキーペアのプライベート部分を含むファイル、すなわち PEM ファイルも必要です。

Linux インスタンス用の Amazon EC2 ユーザーガイドまたは Windows インスタンス用の Amazon EC2ユーザーガイドの接続手順に従うことでこれを行うことができます。接続する際は、開発マシンからインスタンスにファイルを転送できるように接続してください。

Windows で Visual Studio を使用している場合は、Toolkit for Visual Studio を使用してインスタンスに接続することもできます。詳細については、「 ユーザーガイド」の「Amazon EC2 インスタンスへの接続」を参照してください。 AWS Toolkit for Visual Studio

EC2 インスタンスでのサンプルアプリケーションの実行

  1. ローカルドライブからインスタンスにアプリケーションファイルをコピーします。

    転送するファイルは、アプリケーションのビルド方法と、インスタンスに .NET Core Runtime がインストールされているかどうかによって異なります。インスタンスへのファイル転送方法については、Linux インスタンス用の Amazon EC2 ユーザーガイドまたは Windows インスタンス用の Amazon EC2 ユーザーガイドを参照してください。

  2. アプリケーションを起動し、開発マシンと同じ実行結果が得られることを確認します。

  3. アプリケーションで、IAM ロールによって提供されている認証情報が使用されていることを確認します。

    1. Amazon EC2 コンソールを開きます。

    2. インスタンスを選択し、[Actions] (アクション)、[Instance Settings] (インスタンスの設定)、[Attach/Replace IAM Role] (IAM ロールの添付/置換) を使用して IAM ロールをデタッチします。

    3. アプリケーションを再度実行して、認可エラーが返されることを確認します。

クリーンアップ

チュートリアルが終了し、作成した EC2 インスタンスが不要になった場合は、不要な料金が発生しないようにインスタンスを終了してください。この操作は Amazon EC2 コンソールで、または Amazon EC2 インスタンスの終了 の説明に従ってプログラムを使用して実行できます。必要に応じて、このチュートリアル用に作成した他のリソースも削除できます。削除可能なリソースには、IAM ロール、EC2 キーペアと PEM ファイル、セキュリティグループなどがあります。