Use CreatePolicy com um AWS SDK ou CLI - AWS SDKExemplos de código

Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use CreatePolicy com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o CreatePolicy.

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

using System; using System.Threading.Tasks; using Amazon.Organizations; using Amazon.Organizations.Model; /// <summary> /// Creates a new AWS Organizations Policy. /// </summary> public class CreatePolicy { /// <summary> /// Initializes the AWS Organizations client object, uses it to /// create a new Organizations Policy, and then displays information /// about the newly created Policy. /// </summary> public static async Task Main() { IAmazonOrganizations client = new AmazonOrganizationsClient(); var policyContent = "{" + " \"Version\": \"2012-10-17\"," + " \"Statement\" : [{" + " \"Action\" : [\"s3:*\"]," + " \"Effect\" : \"Allow\"," + " \"Resource\" : \"*\"" + "}]" + "}"; try { var response = await client.CreatePolicyAsync(new CreatePolicyRequest { Content = policyContent, Description = "Enables admins of attached accounts to delegate all Amazon S3 permissions", Name = "AllowAllS3Actions", Type = "SERVICE_CONTROL_POLICY", }); Policy policy = response.Policy; Console.WriteLine($"{policy.PolicySummary.Name} has the following content: {policy.Content}"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
  • Para API obter detalhes, consulte CreatePolicyem AWS SDK for .NET APIReferência.

CLI
AWS CLI

Exemplo 1: Para criar uma política com um arquivo de origem de texto para a JSON política

O exemplo a seguir mostra como criar uma política de controle de serviço (SCP) chamadaAllowAllS3Actions. O conteúdo da política provém de um arquivo chamado policy.json presente no computador local.

aws organizations create-policy --content file://policy.json --name AllowAllS3Actions, --type SERVICE_CONTROL_POLICY --description "Allows delegation of all S3 actions"

A saída inclui um objeto de política com detalhes sobre a nova política:

{ "Policy": { "Content": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:*\"],\"Resource\":[\"*\"]}]}", "PolicySummary": { "Arn": "arn:aws:organizations::o-exampleorgid:policy/service_control_policy/p-examplepolicyid111", "Description": "Allows delegation of all S3 actions", "Name": "AllowAllS3Actions", "Type":"SERVICE_CONTROL_POLICY" } } }

Exemplo 2: Para criar uma política com uma JSON política como parâmetro

O exemplo a seguir mostra como criar o mesmoSCP, desta vez incorporando o conteúdo da política como uma JSON string no parâmetro. A string deve ser recuada com barras invertidas antes das aspas duplas para garantir que ela seja tratada como literal no parâmetro (que está entre aspas duplas):

aws organizations create-policy --content "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:*\"],\"Resource\":[\"*\"]}]}" --name AllowAllS3Actions --type SERVICE_CONTROL_POLICY --description "Allows delegation of all S3 actions"

Para obter mais informações sobre como criar e usar políticas em sua organização, consulte Gerenciamento de políticas organizacionais no Guia do usuário do AWS Organizations.

  • Para API obter detalhes, consulte CreatePolicyna Referência de AWS CLI Comandos.

Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

def create_policy(name, description, content, policy_type, orgs_client): """ Creates a policy. :param name: The name of the policy. :param description: The description of the policy. :param content: The policy content as a dict. This is converted to JSON before it is sent to AWS. The specific format depends on the policy type. :param policy_type: The type of the policy. :param orgs_client: The Boto3 Organizations client. :return: The newly created policy. """ try: response = orgs_client.create_policy( Name=name, Description=description, Content=json.dumps(content), Type=policy_type, ) policy = response["Policy"] logger.info("Created policy %s.", name) except ClientError: logger.exception("Couldn't create policy %s.", name) raise else: return policy
  • Para API obter detalhes, consulte a CreatePolicyReferência AWS SDK do Python (Boto3). API