使用 IAM 角色授予访问权限 - Amazon SDK for .NET
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 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 Simple Storage Service 用户指南。有关 Amazon 凭证的更多信息,请参阅使用 Amazon 配置软件开发工具包身份验证

使用以下代码创建 .NET Core 项目。然后在开发计算机上测试该应用程序。

注意

在您的开发计算机上,安装了 .NET Core 运行时系统,这使您无需发布即可运行应用程序。在本教程中稍后创建 EC2 实例时,您可以选择在实例上安装 .NET Core 运行时系统。这为您提供了类似的体验和较小的文件传输。

但是,您也可以选择不在实例上安装 .NET Core 运行时系统。如果您选择此操作方案,则必须发布应用程序,以便在将其转移到实例时包含所有依赖关系。

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. 在导航窗格中,选择角色,然后选择创建角色

  3. 选择 Amazon 服务,找到并选择 EC2,然后选择下一步: 权限

  4. 附加权限策略 下,找到并选择 AmazonS3ReadOnlyAccess。如果愿意,请查看该策略,然后选择下一步: 标签

  5. 如果需要,可以添加标签,然后选择下一步: 查看

  6. 键入角色的名称和描述,然后选择创建角色。请记住此名称,因为在启动 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 Toolkit for Visual Studio 用户指南》中的连接到 Amazon EC2 实例

在 EC2 实例上运行示例应用程序

  1. 将应用程序从本地驱动器复制到您的实例。

    传输哪些文件取决于您如何构建应用程序以及您的实例是否安装了 .NET Core 运行时系统。有关如何将文件传输至实例的信息,请参阅适用于 Linux 实例的 Amazon EC2 用户指南适用于 Windows 实例的 Amazon EC2 用户指南

  2. 启动应用程序并验证其运行结果是否与开发计算机上的结果相同。

  3. 验证应用程序是否使用 IAM 角色提供的凭证。

    1. 打开 Amazon EC2 控制台

    2. 选择实例,然后通过操作实例设置附加/替换 IAM 角色分离 IAM 角色。

    3. 再次运行该应用程序,看看它是否返回了授权错误。

清理

完成本教程后,如果您不再需要自己创建的 EC2 实例,请务必终止该实例以避免不必要的开支。您可以在 Amazon EC2 控制台中或以编程方式执行此操作,如终止 Amazon EC2 实例中所述。您还可以删除为本教程创建的其它资源。其中可能包括 IAM 角色、EC2 密钥对和 PEM 文件、安全组等。