

Der AWS SDK für .NET V3 ist in den Wartungsmodus übergegangen.

Wir empfehlen Ihnen, auf [AWS SDK für .NET V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html) zu migrieren. Weitere Einzelheiten und Informationen zur Migration finden Sie in unserer [Ankündigung zum Wartungsmodus](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/).

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Von IAM verwaltete Richtlinien aus JSON erstellen
<a name="iam-policies-create-json"></a>

Dieses Beispiel zeigt Ihnen, wie Sie mithilfe von eine [IAM-verwaltete Richtlinie aus einem bestimmten Richtliniendokument](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) in JSON erstellen können. AWS SDK für .NET Die Anwendung erstellt ein IAM-Client-Objekt, liest das Richtliniendokument aus einer Datei und erstellt dann die Richtlinie.

**Anmerkung**  
Ein Beispiel für ein Richtliniendokument in JSON finden Sie in den [zusätzlichen Überlegungen](#iam-policies-create-json-additional) am Ende dieses Themas.

Die folgenden Abschnitte enthalten Auszüge aus diesem Beispiel. Der [vollständige Code für das Beispiel](#iam-policies-create-json-complete-code) wird danach angezeigt und kann unverändert erstellt und ausgeführt werden.

**Topics**
+ [Erstellen der -Richtlinie](#iam-policies-create-json-create)
+ [Vollständiger Code](#iam-policies-create-json-complete-code)
+ [Weitere Überlegungen](#iam-policies-create-json-additional)

## Erstellen der -Richtlinie
<a name="iam-policies-create-json-create"></a>

Das folgende Snippet erstellt eine von IAM verwaltete Richtlinie mit dem angegebenen Namen und dem Richtliniendokument.

Das Beispiel [am Ende dieses Themas zeigt, wie dieser](#iam-policies-create-json-complete-code) Codeausschnitt verwendet wird.

```
    //
    // 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)});
    }
```

## Vollständiger Code
<a name="iam-policies-create-json-complete-code"></a>

Dieser Abschnitt enthält relevante Referenzen und den vollständigen Code für dieses Beispiel.

### SDK-Referenzen
<a name="w2aac19c15c19c21c17b5b1"></a>

NuGet Pakete:
+ [AWSSDK.IdentityManagement](https://www.nuget.org/packages/AWSSDK.IdentityManagement)

Elemente der Programmierung:
+ Namespace [Amazon. IdentityManagement](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/NIAM.html)

  Klasse [AmazonIdentityManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TIAMServiceClient.html)
+ Namespace [Amazon. IdentityManagement.Modell](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/NIAMModel.html)

  Klasse [CreatePolicyRequest](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TCreatePolicyRequest.html)

  Klasse [CreatePolicyResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/IAM/TCreatePolicyResponse.html)

### Der Code
<a name="w2aac19c15c19c21c17b7b1"></a>

```
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);
    }
  }

}
```

## Weitere Überlegungen
<a name="iam-policies-create-json-additional"></a>
+ Im Folgenden finden Sie ein Beispiel für ein Richtliniendokument, das Sie in eine JSON-Datei kopieren und als Eingabe für diese Anwendung verwenden können:

------
#### [ 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": "*"
      }
    ]
  }
  ```

------
+ Sie können in der [IAM-Konsole](https://console.aws.amazon.com/iam/home#/policies) überprüfen, ob die Richtlinie erstellt wurde. Wählen Sie in der Dropdownliste **Filterrichtlinien die** Option Vom **Kunden verwaltet** aus. Löschen Sie die Richtlinie, wenn Sie sie nicht mehr benötigen.
+  Weitere Informationen zur Erstellung von Richtlinien finden Sie unter [Erstellen von IAM-Richtlinien](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) und in der [IAM-JSON-Richtlinienreferenz](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html) im [IAM-Benutzerhandbuch](https://docs.aws.amazon.com/IAM/latest/UserGuide/)