のバージョン 4 (V4) SDK for .NET はプレビュー中です。プレビューでこの新しいバージョンに関する情報を確認するには、 AWS SDK for .NET (バージョン 4 プレビュー) デベロッパーガイドを参照してください。
SDK の V4 はプレビュー中であるため、コンテンツは変更される可能性があることに注意してください。
翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
この例では、 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)});
}
コード全文
このセクションでは、例に関連する参考資料とコードの全文を示します。
NuGet パッケージ:
プログラミング要素:
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 コンソール
で確認できます。[Filter policies] (フィルターポリシー) ドロップダウンリストで、[Customer managed] (カスタマー管理) を選択します。ポリシーが不要になった場合は削除します。
-
ポリシー作成の詳細については、IAM ユーザーガイドの「IAM ポリシーの作成」と「IAM JSON ポリシーリファレンス」を参照してください。