为您的创建和列出用户Amazon帐户 - Amazon SDK for .NET
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

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

为您的创建和列出用户Amazon帐户

此示例向您演示如何使用Amazon SDK for .NET创建新的 IAM 用户。使用您向应用程序提供的信息,应用程序创建用户、附加给定的托管策略、获取用户凭据,然后显示您的Amazonaccount.

在你不提供任何命令行参数的情况下,应用程序只是显示你的中所有用户的列表Amazonaccount.

您提供的投入之一是现有托管策略的 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 arguments from the parsed list string userName = CommandLine.GetArgument(parsedArgs, null, "-u", "--user-name"); string policyArn = CommandLine.GetArgument(parsedArgs, null, "-p", "--policy-arn"); string csvFilename = CommandLine.GetArgument(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: "--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 控制台.