通过 JSON 创建 IAM 托管式策略 - Amazon SDK for .NET
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

通过 JSON 创建 IAM 托管式策略

此示例向您展示如何使用Amazon SDK for .NET根据给定的 JSON 策略文档创建 IAM 托管式策略。该应用程序创建 IAM 客户端对象,从文件中读取策略文档,然后创建策略。

注意

有关 JSON 格式的示例策略文档,请参阅本主题末尾的其它注意事项

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

创建策略

以下代码片段使用给定名称和策略文档创建一个 IAM 托管式策略。

本主题末尾的示例显示了此片段的使用情况。

// // Method to create an IAM policy from a JSON file private static async Task<CreatePolicyResponse> CreateManagedPolicy( IAmazonIdentityManagementService iamClient, string policyName, string jsonFilename) { return await iamClient.CreatePolicyAsync(new CreatePolicyRequest{ PolicyName = policyName, PolicyDocument = File.ReadAllText(jsonFilename)}); }

完整代码

本部分显示了本示例的相关参考和完整代码。

using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; namespace IamCreatePolicyFromJson { // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Class to create an IAM policy with a given policy document class Program { private const int MaxArgs = 2; static async Task Main(string[] args) { // Parse the command line and show help if necessary var parsedArgs = CommandLine.Parse(args); if((parsedArgs.Count == 0) || (parsedArgs.Count > MaxArgs)) { PrintHelp(); return; } // Get the application arguments from the parsed list string policyName = CommandLine.GetArgument(parsedArgs, null, "-p", "--policy-name"); string policyFilename = CommandLine.GetArgument(parsedArgs, null, "-j", "--json-filename"); if( string.IsNullOrEmpty(policyName) || (string.IsNullOrEmpty(policyFilename) || !policyFilename.EndsWith(".json"))) CommandLine.ErrorExit( "\nOne or more of the required arguments is missing or incorrect." + "\nRun the command with no arguments to see help."); // Create an IAM service client var iamClient = new AmazonIdentityManagementServiceClient(); // Create the new policy var response = await CreateManagedPolicy(iamClient, policyName, policyFilename); Console.WriteLine($"\nPolicy {response.Policy.PolicyName} has been created."); Console.WriteLine($" Arn: {response.Policy.Arn}"); } // // Method to create an IAM policy from a JSON file private static async Task<CreatePolicyResponse> CreateManagedPolicy( IAmazonIdentityManagementService iamClient, string policyName, string jsonFilename) { return await iamClient.CreatePolicyAsync(new CreatePolicyRequest{ PolicyName = policyName, PolicyDocument = File.ReadAllText(jsonFilename)}); } // // Command-line help private static void PrintHelp() { Console.WriteLine( "\nUsage: IamCreatePolicyFromJson -p <policy-name> -j <json-filename>" + "\n -p, --policy-name: The name you want the new policy to have." + "\n -j, --json-filename: The name of the JSON file with the policy document."); } } // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // 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); } } }

其他注意事项

  • 以下是示例策略文档,您可以将其复制到 JSON 文件中并用作此应用程序的输入:

    { "Version" : "2012-10-17", "Id" : "DotnetTutorialPolicy", "Statement" : [ { "Sid" : "DotnetTutorialPolicyS3", "Effect" : "Allow", "Action" : [ "s3:Get*", "s3:List*" ], "Resource" : "*" }, { "Sid" : "DotnetTutorialPolicyPolly", "Effect": "Allow", "Action": [ "polly:DescribeVoices", "polly:SynthesizeSpeech" ], "Resource": "*" } ] }
  • 您可以通过查看 IAM 控制台来验证策略是否已创建。使用筛选策略下拉菜单,选择客户托管。在您不再需要策略时将其删除。