本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用 IAM 角色授予访问权限
本教程向您演示如何使用Amazon SDK for .NET在 Amazon EC2 实例上启用 IAM 角色。
概览
所有请求Amazon必须通过使用颁发的凭证进行加密签名Amazon. 因此,您需要通过某种策略为 Amazon EC2 实例上运行的应用程序管理凭证。您必须以安全的方式分发、存储和轮换这些凭证,并且能让应用程序访问这些凭证。
使用 IAM 角色,您可以有效地管理这些证书。您可以创建 IAM 角色并将其配置为应用程序所需的权限,然后将该角色附加到 EC2 实例。《》中的有关使用 IAM 角色的好处的更多信息适用于 Linux 实例的 Amazon EC2;或者适用于 Windows 实例的Amazon EC2 用户指南. 另请参阅有关的信息IAM 角色(在 IAM 用户指南中)。
对于使用以下方法构建的应用程序Amazon SDK for .NET,当应用程序为一个构造一个客户端对象时Amazon服务,该对象从多个潜在来源搜索凭证。其中显示的搜索顺序凭证和配置文件解析.
如果客户端对象找不到来自任何其他来源的凭证,它会检索与 IAM 角色中配置的具有相同权限的临时凭证,并且位于 EC2 实例的元数据中。这些凭证用于调用Amazon来自客户端对象。
关于本教程
在您学习本教程时,您将使用Amazon SDK for .NET(和其他工具)启动附加了 IAM 角色的 Amazon EC2 实例,然后使用 IAM 角色的权限查看该实例上的应用程序。
创建示例 Amazon S3 应用程序
此示例应用程序从 Amazon S3 中检索一个数据元。要运行应用程序,您需要满足以下条件:
-
包含文本文件的 Amazon S3 存储桶。
-
Amazon您的开发计算机上允许您访问存储段的证书。
有关创建 Amazon S3 存储桶和上提供了一个对象的信息,请参阅Amazon S3 入门指南. 有关的信息Amazon证书,请参阅配置Amazon证书.
使用以下代码创建 .NET Core 项目。然后在您的开发计算机上测试应用程序。
在开发计算机上安装了 .NET Core Runtime,这使您无需发布即可运行应用程序。在本教程中稍后创建 EC2 实例时,您可以选择在该实例上安装 .NET Core Runtime。这为您提供了类似的体验和更小的文件传输。
但是,您也可以选择不在实例上安装 .NET Core Runtime。如果您选择此操作方针,则必须发布应用程序,以便在将其传输到实例时包含所有依赖关系。
NuGet 软件包:
编程元素:
-
命名空间Amazon.S3
Class亚马逊 S3 客户端
-
命名空间Amazon.......
ClassGetObjectResponse
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 角色。
-
打开 IAM 控制台
。 -
在导航窗格中,选择角色,然后选择创建角色.
-
SelectAmazon服务,找到并选择EC2,然后选择后续:Permissions (下一步:权限)。
-
unDet附加权限策略,找到并选择亚马逊 S3ReadOnlyAccess. 如果需要,请检查策略,然后选择后续:标签。
-
根据需要添加标签,然后选择后续:审核。
-
键入角色的名称和描述,然后选择创建角色。请记住此名称,因为在启动 EC2 实例时会用到它。
启动 EC2 实例并附加 IAM 角色
启动一个 EC2 实例,该实例具有您之前创建的 IAM 角色。您可以通过以下方式来执行此操作。
-
使用 EC2 控制台
按照说明在中启动实例适用于 Linux 实例的 Amazon EC2;或者适用于 Windows 实例的Amazon EC2 用户指南.
当你浏览向导时,你至少应该访问配置实例详细信息页面,这样你就可以选择IAM 角色您之前创建的。
-
使用 Amazon SDK for .NET
有关此问题的信息,请参阅启动 Amazon EC2 实例,包括其它注意事项 该主题快要结束了。
要启动附加了 IAM 角色的 EC2 实例,IAM 用户的配置必须包含特定的权限。有关所需权限的更多信息,请参阅适用于 Linux 实例的 Amazon EC2;或者适用于 Windows 实例的Amazon EC2 用户指南.
Connect 到 EC2 实例
Connect 到 EC2 实例,这样您就可以将示例应用程序传输到该实例,然后运行该应用程序。您需要包含用于启动实例的key pair 的私有部分的文件;即 PEM 文件。
您可以通过以下步骤中的连接步骤实现上述目的适用于 Linux 实例的 Amazon EC2;或者适用于 Windows 实例的Amazon EC2 用户指南. 连接时,应确保您可以将文件从开发计算机传输到您的实例。
如果你在 Windows 上使用 Visual Studio,你也可以使用 Toolkit for Visual Studio 连接到实例。有关更多信息,请参阅连接到 Amazon EC2 实例中的Amazon Toolkit for Visual Studio用户指南。
在 EC2 实例上运行示例应用程序
-
将应用程序文件从本地驱动器复制到您的实例。
传输哪些文件取决于您构建应用程序的方式以及您的实例是否安装了 .NET Core Runtime。有关如何将文件传输到实例的信息,请参阅适用于 Linux 实例的 Amazon EC2;或者适用于 Windows 实例的Amazon EC2 用户指南.
-
启动应用程序并验证其运行结果是否与在开发计算机上运行的结果相同。
-
验证应用程序是否使用了 IAM 角色提供的证书。
-
打开 Amazon EC2 控制台
。 -
选择实例并通过分离 IAM 角色操作、实例设置、附加/替换 IAM 角色.
-
再次运行应用程序,看看它返回了授权错误。
-
清除
完成本教程后,如果您不再需要创建的 EC2 实例,请务必终止该实例以避免不必要的成本。您可以在Amazon EC2 控制台