CreatePolicyÚselo con un AWS SDK o CLI - AWS SDKEjemplos de código

Hay más AWS SDK ejemplos disponibles en el GitHub repositorio de AWS Doc SDK Examples.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

CreatePolicyÚselo con un AWS SDK o CLI

En los siguientes ejemplos de código, se muestra cómo utilizar CreatePolicy.

.NET
AWS SDK for .NET
nota

Hay más en marcha GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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 obtener más información, consulte CreatePolicyla AWS SDK for .NET APIReferencia.

CLI
AWS CLI

Ejemplo 1: Para crear una política con un archivo fuente de texto para la JSON política

El siguiente ejemplo muestra cómo crear una política de control de servicios (SCP) denominadaAllowAllS3Actions. El contenido de la política se extrae de un archivo del equipo local denominado policy.json.

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

La salida incluye un objeto de política con detalles sobre la nueva 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" } } }

Ejemplo 2: Para crear una política con una JSON política como parámetro

El siguiente ejemplo muestra cómo crearlaSCP, esta vez incrustando el contenido de la política en forma de JSON cadena en el parámetro. La cadena debe aplicar una secuencia de escape con barras diagonales antes de las comillas dobles para garantizar que se traten como literales en el parámetro, que a su vez queda rodeado de comillas dobles:

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 obtener más información sobre la creación y el uso de políticas en su organización, consulte Administración de políticas de la organización en la Guía del usuario de AWS Organizations.

  • Para API obtener más información, consulte CreatePolicyla Referencia de AWS CLI comandos.

Python
SDKpara Python (Boto3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de 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 obtener más información, consulte CreatePolicyla AWS SDKreferencia de Python (Boto3). API