创建并列出您的用户 AWS 账户 - 适用于 .NET 的 AWS 开发工具包
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 AWS 服务入门

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

创建并列出您的用户 AWS 账户

此示例向您展示如何使用 适用于 .NET 的 AWS 开发工具包 创建新的IAM用户。使用您提供给应用程序的信息,它创建用户、附加给定的管理策略、获取用户的凭证,然后显示您 AWS 帐户。

如果您不提供任何命令行参数,应用程序只需显示您 AWS 帐户。

您提供的输入之一是现有管理策略的Amazon资源名称(ARN)。您可以在 IAM控制台.

以下部分提供了此示例的片段。的 示例的完整代码 之后显示,并且可以按原样构建和运行。

创建用户。

以下代码段创建 IAM 用户,添加给定的托管安全策略,然后为用户创建和存储凭证。

示例 在本主题结束时 显示此片段正在使用。

// // Method to create the user private static async Task<CreateUserResponse> CreateUser( IAmazonIdentityManagementService iamClient, string userName, string policyArn, string csvFilename) { // Create the user // Could also create a login profile for the user by using CreateLoginProfileAsync CreateUserResponse responseCreate = await iamClient.CreateUserAsync(new CreateUserRequest(userName)); // Attach an existing managed policy await iamClient.AttachUserPolicyAsync(new AttachUserPolicyRequest{ UserName = responseCreate.User.UserName, PolicyArn = policyArn}); // Create credentials and write them to a CSV file. CreateAccessKeyResponse responseCreds = await iamClient.CreateAccessKeyAsync(new CreateAccessKeyRequest{ UserName = responseCreate.User.UserName}); using (FileStream s = new FileStream(csvFilename, FileMode.Create)) using (StreamWriter writer = new StreamWriter(s)) { writer.WriteLine("User name,Access key ID,Secret access key"); writer.WriteLine("{0},{1},{2}", responseCreds.AccessKey.UserName, responseCreds.AccessKey.AccessKeyId, responseCreds.AccessKey.SecretAccessKey); } return responseCreate; }

显示用户列表

以下代码段显示现有用户列表,以及有关每个用户的信息,例如访问密钥ID和附加策略。

示例 在本主题结束时 显示此片段正在使用。

// // Method to print out a list of the existing users and information about them private static async Task ListUsers(IAmazonIdentityManagementService iamClient) { // Get the list of users ListUsersResponse responseUsers = await iamClient.ListUsersAsync(); Console.WriteLine("\nFull list of users..."); foreach (var user in responseUsers.Users) { Console.WriteLine($"User {user.UserName}:"); Console.WriteLine($"\tCreated: {user.CreateDate.ToShortDateString()}"); // Show the list of groups this user is part of ListGroupsForUserResponse responseGroups = await iamClient.ListGroupsForUserAsync( new ListGroupsForUserRequest(user.UserName)); foreach (var group in responseGroups.Groups) Console.WriteLine($"\tGroup: {group.GroupName}"); // Show the list of access keys for this user ListAccessKeysResponse responseAccessKeys = await iamClient.ListAccessKeysAsync( new ListAccessKeysRequest{UserName = user.UserName}); foreach(AccessKeyMetadata accessKey in responseAccessKeys.AccessKeyMetadata) Console.WriteLine($"\tAccess key ID: {accessKey.AccessKeyId}"); // Show the list of managed policies attached to this user var requestManagedPolicies = new ListAttachedUserPoliciesRequest{ UserName = user.UserName}; ListAttachedUserPoliciesResponse responseManagedPolicies = await iamClient.ListAttachedUserPoliciesAsync( new ListAttachedUserPoliciesRequest{UserName = user.UserName}); foreach(var policy in responseManagedPolicies.AttachedPolicies) Console.WriteLine($"\tManaged policy name: {policy.PolicyName}"); // Show the list of inline policies attached to this user ListUserPoliciesResponse responseInlinePolicies = await iamClient.ListUserPoliciesAsync( new ListUserPoliciesRequest(user.UserName)); foreach(var policy in responseInlinePolicies.PolicyNames) Console.WriteLine($"\tInline policy name: {policy}"); } }

完整代码

本节显示此示例的相关参考和完整代码。

using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; namespace IamCreateUser { // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class to create a user class Program { private const int MaxArgs = 3; static async Task Main(string[] args) { // Create an IAM service client var iamClient = new AmazonIdentityManagementServiceClient(); // Parse the command line and show help if necessary var parsedArgs = CommandLine.Parse(args); if((parsedArgs.Count == 0) || (parsedArgs.Count > MaxArgs)) { PrintHelp(); Console.WriteLine("\nIncorrect number of arguments specified."); Console.Write("Do you want to see a list of the existing users? ((y) or n): "); string response = Console.ReadLine(); if((string.IsNullOrEmpty(response)) || (response.ToLower() == "y")) await ListUsers(iamClient); return; } // Get the application parameters from the parsed arguments string userName = CommandLine.GetParameter(parsedArgs, null, "-u", "--user-name"); string policyArn = CommandLine.GetParameter(parsedArgs, null, "-p", "--policy-arn"); string csvFilename = CommandLine.GetParameter(parsedArgs, null, "-c", "--csv-filename"); if( (string.IsNullOrEmpty(policyArn) || !policyArn.StartsWith("arn:")) || (string.IsNullOrEmpty(csvFilename) || !csvFilename.EndsWith(".csv")) || (string.IsNullOrEmpty(userName))) CommandLine.ErrorExit( "\nOne or more of the required arguments is missing or incorrect." + "\nRun the command with no arguments to see help."); // Create a user, attach a managed policy, and obtain credentials var responseCreate = await CreateUser(iamClient, userName, policyArn, csvFilename); Console.WriteLine($"\nUser {responseCreate.User.UserName} was created."); Console.WriteLine($"User ID: {responseCreate.User.UserId}"); // Output a list of the existing users await ListUsers(iamClient); } // // Method to create the user private static async Task<CreateUserResponse> CreateUser( IAmazonIdentityManagementService iamClient, string userName, string policyArn, string csvFilename) { // Create the user // Could also create a login profile for the user by using CreateLoginProfileAsync CreateUserResponse responseCreate = await iamClient.CreateUserAsync(new CreateUserRequest(userName)); // Attach an existing managed policy await iamClient.AttachUserPolicyAsync(new AttachUserPolicyRequest{ UserName = responseCreate.User.UserName, PolicyArn = policyArn}); // Create credentials and write them to a CSV file. CreateAccessKeyResponse responseCreds = await iamClient.CreateAccessKeyAsync(new CreateAccessKeyRequest{ UserName = responseCreate.User.UserName}); using (FileStream s = new FileStream(csvFilename, FileMode.Create)) using (StreamWriter writer = new StreamWriter(s)) { writer.WriteLine("User name,Access key ID,Secret access key"); writer.WriteLine("{0},{1},{2}", responseCreds.AccessKey.UserName, responseCreds.AccessKey.AccessKeyId, responseCreds.AccessKey.SecretAccessKey); } return responseCreate; } // // Method to print out a list of the existing users and information about them private static async Task ListUsers(IAmazonIdentityManagementService iamClient) { // Get the list of users ListUsersResponse responseUsers = await iamClient.ListUsersAsync(); Console.WriteLine("\nFull list of users..."); foreach (var user in responseUsers.Users) { Console.WriteLine($"User {user.UserName}:"); Console.WriteLine($"\tCreated: {user.CreateDate.ToShortDateString()}"); // Show the list of groups this user is part of ListGroupsForUserResponse responseGroups = await iamClient.ListGroupsForUserAsync( new ListGroupsForUserRequest(user.UserName)); foreach (var group in responseGroups.Groups) Console.WriteLine($"\tGroup: {group.GroupName}"); // Show the list of access keys for this user ListAccessKeysResponse responseAccessKeys = await iamClient.ListAccessKeysAsync( new ListAccessKeysRequest{UserName = user.UserName}); foreach(AccessKeyMetadata accessKey in responseAccessKeys.AccessKeyMetadata) Console.WriteLine($"\tAccess key ID: {accessKey.AccessKeyId}"); // Show the list of managed policies attached to this user var requestManagedPolicies = new ListAttachedUserPoliciesRequest{ UserName = user.UserName}; ListAttachedUserPoliciesResponse responseManagedPolicies = await iamClient.ListAttachedUserPoliciesAsync( new ListAttachedUserPoliciesRequest{UserName = user.UserName}); foreach(var policy in responseManagedPolicies.AttachedPolicies) Console.WriteLine($"\tManaged policy name: {policy.PolicyName}"); // Show the list of inline policies attached to this user ListUserPoliciesResponse responseInlinePolicies = await iamClient.ListUserPoliciesAsync( new ListUserPoliciesRequest(user.UserName)); foreach(var policy in responseInlinePolicies.PolicyNames) Console.WriteLine($"\tInline policy name: {policy}"); } } // // Command-line help private static void PrintHelp() { Console.WriteLine( "\nUsage: IamCreateUser -u <user-name> -p <policy-arn> -c <csv-filename>" + "\n -u, --user-name: The name of the user you want to create." + "\n -p, --policy-arn: The ARN of an existing managed policy." + "\n -c, --csv-filename: The name of a .csv file to write the credentials 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: "--param value" or "-p value". // If "param" is found without a matching "value", Dictionary.Value is an empty string. // If "value" is found without a matching "param", Dictionary.Key is "--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 = string.Empty; // Is there 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 a parameter from the parsed command-line arguments public static string GetParameter( Dictionary<string,string> parsedArgs, string def, params string[] keys) { string retval = null; foreach(var key in keys) if(parsedArgs.TryGetValue(key, out retval)) break; return retval ?? def; } // // Exit with an error. public static void ErrorExit(string msg, int code=1) { Console.WriteLine("\nError"); Console.WriteLine(msg); Environment.Exit(code); } } }

其他注意事项