Requisitos previos - AWS Config

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.

Requisitos previos

Antes de AWS configurarlo AWS CLI, debe crear un bucket de Amazon S3, un tema de Amazon SNS y un rol de IAM con políticas adjuntas como requisitos previos. A continuación, puede usar el AWS CLI para especificar el bucket, el tema y el rol. AWS Config Siga este procedimiento para configurar sus requisitos previos para AWS Config.

Creación del bucket de Amazon S3

Si ya tiene un bucket de Amazon S3 en su cuenta y desea utilizarlo, omita este paso y vaya a Creación de un tema de Amazon SNS.

Creación de un bucket
  1. Abra la consola de Amazon S3 en https://console.aws.amazon.com/s3.

  2. Elija Crear bucket.

  3. En Nombre del bucket, escriba un nombre compatible con DNS para el bucket.

    El nombre del bucket debe:

    • Ser único en todo Amazon S3.

    • Tener entre 3 y 63 caracteres.

    • No contiene caracteres en mayúsculas.

    • Comenzar por una letra minúscula o un número.

    Una vez que haya creado el bucket, no podrá modificar su nombre. Asegúrese de que el nombre del bucket que elija sea único entre todos los nombres de buckets de Amazon S3. Para obtener más información acerca de las convenciones de nomenclatura de buckets de Amazon S3, consulte Restricciones y limitaciones de los buckets en la Guía del usuario de Amazon Simple Storage Service.

    importante

    Evita incluir información confidencial en el nombre del bucket. El nombre del bucket será visible en las URL que señalan a los objetos almacenados en él.

  4. En Región, elige la AWS región en la que quieres que resida el depósito.

    Puede seleccionar una región cercana para minimizar la latencia y los costos, así como para satisfacer los requisitos reglamentarios. Los objetos almacenados en una región nunca abandonarán esa región salvo que usted los transfiera de forma específica a otra. Para obtener una lista de AWS las regiones de Amazon S3, consulte los puntos AWS de enlace del Referencia general de Amazon Web Servicesservicio en.

  5. En Configuración del bucket para Block Public Access, elija la configuración de Block Public Access que desee aplicar al bucket.

    Le recomendamos que deje todas las configuraciones habilitadas a menos que sepa que necesita desactivar una o varias de ellas para su caso de uso, como alojar un sitio web público. La configuración de acceso público de bloqueo que habilite para el bucket también se habilitará para todos los puntos de acceso que cree en el bucket. Para obtener más información acerca del bloqueo de acceso público, consulte Usar el bloqueo de acceso público de Amazon S3 en la Guía del usuario de Amazon Simple Storage Service.

  6. (Opcional) Si desea habilitar Bloqueo de objetos en S3, realice las siguientes acciones:

    1. Elija Configuración avanzada y lea el mensaje que aparece.

      importante

      Solo se puede habilitar Bloqueo de objetos en S3 para un bucket cuando se crea. Si habilita Bloqueo de objetos para el bucket, no podrá deshabilitarlo más adelante. Al habilitar Bloqueo de objetos, también se habilita el control de versiones para el bucket. Después de habilitar Bloqueo de objetos para el bucket, debe configurar los valores de Bloqueo de objetos antes de proteger los objetos del bucket. Para obtener más información acerca de cómo configurar la protección para objetos, consulte Configuring S3 Object Lock using the Amazon S3 console.

    2. Si desea habilitar el bloqueo de objetos, escriba enable (habilitar) en el cuadro de texto y elija Confirm (Confirmar).

    Para obtener más información acerca de la función Bloqueo de objetos en S3, consulte Usar Bloqueo de objetos de S3 en la Guía del usuario de Amazon Simple Storage Service.

  7. Elija Crear bucket.

Cuando utilizas los AWS SDK para crear un depósito, debes crear un cliente y, a continuación, utilizar el cliente para enviar una solicitud de creación de un depósito. Como práctica recomendada, debe crear el cliente y el bucket en la misma Región de AWS. Si no especifica una región al crear un cliente o un bucket, Amazon S3 utiliza la región predeterminada, EE. UU. Este (Norte de Virginia).

Para crear un cliente que pueda acceder a un punto final de doble pila, debes especificar un. Región de AWS Para obtener más información, consulte Puntos de enlace de doble pila en Amazon S3. Para obtener una lista de los disponibles Regiones de AWS, consulte Regiones y puntos finales en el. Referencia general de AWS

Al crear un cliente, la región se asigna al punto de conexión específico de la región. El cliente utiliza este punto de conexión para comunicarse con Amazon S3: s3.<region>.amazonaws.com. Si su región se lanzó después del 20 de marzo de 2019, su cliente y el bucket deben estar en la misma región. Sin embargo, puede utilizar un cliente en la región EE. UU. Este (Norte de Virginia) para crear un bucket en cualquier región que se haya lanzado antes del 20 de marzo de 2019. Para obtener más información, consulte Puntos de conexión heredados.

Estos ejemplos de código del AWS SDK realizan las siguientes tareas:

  • Crear un cliente mediante la especificación explícita de una Región de AWS: en el ejemplo, el cliente utiliza el punto de conexión s3.us-west-2.amazonaws.com para comunicarse con Amazon S3. Puede especificar cualquier Región de AWS. Para obtener una lista Regiones de AWS, consulte Regiones y puntos finales en la Referencia AWS general.

  • Enviar una solicitud de creación de bucket al especificar solo un nombre de bucket: el cliente envía una solicitud a Amazon S3 para crear el bucket en la región donde usted creó un cliente.

  • Recuperar la información acerca de la ubicación del bucket: Amazon S3 almacena información de la ubicación del bucket en el subrecurso location asociado con el bucket.

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

.NET
AWS SDK for .NET
nota

Hay más información sobre. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Shows how to create a new Amazon S3 bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the bucket to create.</param> /// <returns>A boolean value representing the success or failure of /// the bucket creation process.</returns> public static async Task<bool> CreateBucketAsync(IAmazonS3 client, string bucketName) { try { var request = new PutBucketRequest { BucketName = bucketName, UseClientRegion = true, }; var response = await client.PutBucketAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error creating bucket: '{ex.Message}'"); return false; } }

Cree un nuevo bucket con el bloqueo de objetos habilitado.

/// <summary> /// Create a new Amazon S3 bucket with object lock actions. /// </summary> /// <param name="bucketName">The name of the bucket to create.</param> /// <param name="enableObjectLock">True to enable object lock on the bucket.</param> /// <returns>True if successful.</returns> public async Task<bool> CreateBucketWithObjectLock(string bucketName, bool enableObjectLock) { Console.WriteLine($"\tCreating bucket {bucketName} with object lock {enableObjectLock}."); try { var request = new PutBucketRequest { BucketName = bucketName, UseClientRegion = true, ObjectLockEnabledForBucket = enableObjectLock, }; var response = await _amazonS3.PutBucketAsync(request); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error creating bucket: '{ex.Message}'"); return false; } }
  • Para obtener más información sobre la API, consulta CreateBucketla Referencia AWS SDK for .NET de la API.

Bash
AWS CLI con el script Bash
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.

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function create-bucket # # This function creates the specified bucket in the specified AWS Region, unless # it already exists. # # Parameters: # -b bucket_name -- The name of the bucket to create. # -r region_code -- The code for an AWS Region in which to # create the bucket. # # Returns: # The URL of the bucket that was created. # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function create_bucket() { local bucket_name region_code response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function create_bucket" echo "Creates an Amazon S3 bucket. You must supply a bucket name:" echo " -b bucket_name The name of the bucket. It must be globally unique." echo " [-r region_code] The code for an AWS Region in which the bucket is created." echo "" } # Retrieve the calling parameters. while getopts "b:r:h" option; do case "${option}" in b) bucket_name="${OPTARG}" ;; r) region_code="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done if [[ -z "$bucket_name" ]]; then errecho "ERROR: You must provide a bucket name with the -b parameter." usage return 1 fi local bucket_config_arg # A location constraint for "us-east-1" returns an error. if [[ -n "$region_code" ]] && [[ "$region_code" != "us-east-1" ]]; then bucket_config_arg="--create-bucket-configuration LocationConstraint=$region_code" fi iecho "Parameters:\n" iecho " Bucket name: $bucket_name" iecho " Region code: $region_code" iecho "" # If the bucket already exists, we don't want to try to create it. if (bucket_exists "$bucket_name"); then errecho "ERROR: A bucket with that name already exists. Try again." return 1 fi # shellcheck disable=SC2086 response=$(aws s3api create-bucket \ --bucket "$bucket_name" \ $bucket_config_arg) # shellcheck disable=SC2181 if [[ ${?} -ne 0 ]]; then errecho "ERROR: AWS reports create-bucket operation failed.\n$response" return 1 fi }
  • Para obtener más información sobre la API, consulta CreateBucketla Referencia de AWS CLI comandos.

C++
SDK para C++
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

bool AwsDoc::S3::CreateBucket(const Aws::String &bucketName, const Aws::Client::ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::CreateBucketRequest request; request.SetBucket(bucketName); //TODO(user): Change the bucket location constraint enum to your target Region. if (clientConfig.region != "us-east-1") { Aws::S3::Model::CreateBucketConfiguration createBucketConfig; createBucketConfig.SetLocationConstraint( Aws::S3::Model::BucketLocationConstraintMapper::GetBucketLocationConstraintForName( clientConfig.region)); request.SetCreateBucketConfiguration(createBucketConfig); } Aws::S3::Model::CreateBucketOutcome outcome = client.CreateBucket(request); if (!outcome.IsSuccess()) { auto err = outcome.GetError(); std::cerr << "Error: CreateBucket: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "Created bucket " << bucketName << " in the specified AWS Region." << std::endl; } return outcome.IsSuccess(); }
  • Para obtener más información sobre la API, consulta CreateBucketla Referencia AWS SDK for C++ de la API.

CLI
AWS CLI

Ejemplo 1: Creación de un bucket

En los siguientes ejemplos de create-bucket se crea un bucket denominado my-bucket:

aws s3api create-bucket \ --bucket my-bucket \ --region us-east-1

Salida:

{ "Location": "/my-bucket" }

Para obtener más información, consulte Crear un bucket en la Guía del usuario de Amazon S3.

Ejemplo 2: Creación de un bucket con propietario obligatorio

En el siguiente ejemplo de create-bucket se crea un bucket denominado my-bucket que utiliza la configuración Aplicada al propietario del bucket de S3 Object Ownership.

aws s3api create-bucket \ --bucket my-bucket \ --region us-east-1 \ --object-ownership BucketOwnerEnforced

Salida:

{ "Location": "/my-bucket" }

Para obtener más información, consulte Control de la propiedad de objetos y desactivación de las ACL en la Guía del usuario de Amazon S3.

Ejemplo 3: Creación de un bucket fuera de la región ``us-east-1``

En el siguiente ejemplo create-bucket, se crea un bucket denominado my-bucket en la región eu-west-1. Las regiones situadas fuera de us-east-1 requieren que se especifique el LocationConstraint correspondiente para poder crear el bucket en la región deseada.

aws s3api create-bucket \ --bucket my-bucket \ --region eu-west-1 \ --create-bucket-configuration LocationConstraint=eu-west-1

Salida:

{ "Location": "http://my-bucket.s3.amazonaws.com/" }

Para obtener más información, consulte Crear un bucket en la Guía del usuario de Amazon S3.

  • Para obtener más información sobre la API, consulta CreateBucketla Referencia de AWS CLI comandos.

Go
SDK para Go V2
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions // used in the examples. // It contains S3Client, an Amazon S3 service client that is used to perform bucket // and object actions. type BucketBasics struct { S3Client *s3.Client } // CreateBucket creates a bucket with the specified name in the specified Region. func (basics BucketBasics) CreateBucket(name string, region string) error { _, err := basics.S3Client.CreateBucket(context.TODO(), &s3.CreateBucketInput{ Bucket: aws.String(name), CreateBucketConfiguration: &types.CreateBucketConfiguration{ LocationConstraint: types.BucketLocationConstraint(region), }, }) if err != nil { log.Printf("Couldn't create bucket %v in Region %v. Here's why: %v\n", name, region, err) } return err }
  • Para obtener más información sobre la API, consulta CreateBucketla Referencia AWS SDK for Go de la API.

Java
SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Crear un bucket.

import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.HeadBucketRequest; import software.amazon.awssdk.services.s3.model.HeadBucketResponse; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.waiters.S3Waiter; import java.net.URISyntaxException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateBucket { public static void main(String[] args) throws URISyntaxException { final String usage = """ Usage: <bucketName>\s Where: bucketName - The name of the bucket to create. The bucket name must be unique, or an error occurs. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; System.out.format("Creating a bucket named %s\n", bucketName); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); createBucket(s3, bucketName); s3.close(); } public static void createBucket(S3Client s3Client, String bucketName) { try { S3Waiter s3Waiter = s3Client.waiter(); CreateBucketRequest bucketRequest = CreateBucketRequest.builder() .bucket(bucketName) .build(); s3Client.createBucket(bucketRequest); HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() .bucket(bucketName) .build(); // Wait until the bucket is created and print out the response. WaiterResponse<HeadBucketResponse> waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println(bucketName + " is ready"); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

Cree un nuevo bucket con el bloqueo de objetos habilitado.

// Create a new Amazon S3 bucket with object lock options. public void createBucketWithLockOptions(boolean enableObjectLock, String bucketName) { S3Waiter s3Waiter = getClient().waiter(); CreateBucketRequest bucketRequest = CreateBucketRequest.builder() .bucket(bucketName) .objectLockEnabledForBucket(enableObjectLock) .build(); getClient().createBucket(bucketRequest); HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() .bucket(bucketName) .build(); // Wait until the bucket is created and print out the response. s3Waiter.waitUntilBucketExists(bucketRequestWait); System.out.println(bucketName + " is ready"); }
  • Para obtener más información sobre la API, consulta CreateBucketla Referencia AWS SDK for Java 2.x de la API.

JavaScript
SDK para JavaScript (v3)
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.

Crear el bucket.

import { CreateBucketCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new CreateBucketCommand({ // The name of the bucket. Bucket names are unique and have several other constraints. // See https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html Bucket: "bucket-name", }); try { const { Location } = await client.send(command); console.log(`Bucket created with location ${Location}`); } catch (err) { console.error(err); } };
Kotlin
SDK para Kotlin
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

suspend fun createNewBucket(bucketName: String) { val request = CreateBucketRequest { bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> s3.createBucket(request) println("$bucketName is ready") } }
  • Para obtener más información sobre la API, consulta CreateBucketla referencia sobre el AWS SDK para la API de Kotlin.

PHP
SDK para PHP
nota

Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Crear un bucket.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $this->s3client->createBucket([ 'Bucket' => $this->bucketName, 'CreateBucketConfiguration' => ['LocationConstraint' => $region], ]); echo "Created bucket named: $this->bucketName \n"; } catch (Exception $exception) { echo "Failed to create bucket $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with bucket creation before continuing."); }
  • Para obtener más información sobre la API, consulta CreateBucketla Referencia AWS SDK for PHP de la API.

Python
SDK para Python (Boto3)
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Cree un bucket con la configuración predeterminada.

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name def create(self, region_override=None): """ Create an Amazon S3 bucket in the default Region for the account or in the specified Region. :param region_override: The Region in which to create the bucket. If this is not specified, the Region configured in your shared credentials is used. """ if region_override is not None: region = region_override else: region = self.bucket.meta.client.meta.region_name try: self.bucket.create(CreateBucketConfiguration={"LocationConstraint": region}) self.bucket.wait_until_exists() logger.info("Created bucket '%s' in region=%s", self.bucket.name, region) except ClientError as error: logger.exception( "Couldn't create bucket named '%s' in region=%s.", self.bucket.name, region, ) raise error

Cree un bucket con control de versiones con una configuración de ciclo de vida.

def create_versioned_bucket(bucket_name, prefix): """ Creates an Amazon S3 bucket, enables it for versioning, and configures a lifecycle that expires noncurrent object versions after 7 days. Adding a lifecycle configuration to a versioned bucket is a best practice. It helps prevent objects in the bucket from accumulating a large number of noncurrent versions, which can slow down request performance. Usage is shown in the usage_demo_single_object function at the end of this module. :param bucket_name: The name of the bucket to create. :param prefix: Identifies which objects are automatically expired under the configured lifecycle rules. :return: The newly created bucket. """ try: bucket = s3.create_bucket( Bucket=bucket_name, CreateBucketConfiguration={ "LocationConstraint": s3.meta.client.meta.region_name }, ) logger.info("Created bucket %s.", bucket.name) except ClientError as error: if error.response["Error"]["Code"] == "BucketAlreadyOwnedByYou": logger.warning("Bucket %s already exists! Using it.", bucket_name) bucket = s3.Bucket(bucket_name) else: logger.exception("Couldn't create bucket %s.", bucket_name) raise try: bucket.Versioning().enable() logger.info("Enabled versioning on bucket %s.", bucket.name) except ClientError: logger.exception("Couldn't enable versioning on bucket %s.", bucket.name) raise try: expiration = 7 bucket.LifecycleConfiguration().put( LifecycleConfiguration={ "Rules": [ { "Status": "Enabled", "Prefix": prefix, "NoncurrentVersionExpiration": {"NoncurrentDays": expiration}, } ] } ) logger.info( "Configured lifecycle to expire noncurrent versions after %s days " "on bucket %s.", expiration, bucket.name, ) except ClientError as error: logger.warning( "Couldn't configure lifecycle on bucket %s because %s. " "Continuing anyway.", bucket.name, error, ) return bucket
  • Para obtener más información sobre la API, consulta CreateBucketla AWS Referencia de API de SDK for Python (Boto3).

Ruby
SDK para Ruby
nota

Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

require "aws-sdk-s3" # Wraps Amazon S3 bucket actions. class BucketCreateWrapper attr_reader :bucket # @param bucket [Aws::S3::Bucket] An Amazon S3 bucket initialized with a name. This is a client-side object until # create is called. def initialize(bucket) @bucket = bucket end # Creates an Amazon S3 bucket in the specified AWS Region. # # @param region [String] The Region where the bucket is created. # @return [Boolean] True when the bucket is created; otherwise, false. def create?(region) @bucket.create(create_bucket_configuration: { location_constraint: region }) true rescue Aws::Errors::ServiceError => e puts "Couldn't create bucket. Here's why: #{e.message}" false end # Gets the Region where the bucket is located. # # @return [String] The location of the bucket. def location if @bucket.nil? "None. You must create a bucket before you can get its location!" else @bucket.client.get_bucket_location(bucket: @bucket.name).location_constraint end rescue Aws::Errors::ServiceError => e "Couldn't get the location of #{@bucket.name}. Here's why: #{e.message}" end end # Example usage: def run_demo region = "us-west-2" wrapper = BucketCreateWrapper.new(Aws::S3::Bucket.new("doc-example-bucket-#{Random.uuid}")) return unless wrapper.create?(region) puts "Created bucket #{wrapper.bucket.name}." puts "Your bucket's region is: #{wrapper.location}" end run_demo if $PROGRAM_NAME == __FILE__
  • Para obtener más información sobre la API, consulta CreateBucketla Referencia AWS SDK for Ruby de la API.

Rust
SDK para Rust
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

pub async fn create_bucket( client: &Client, bucket_name: &str, region: &str, ) -> Result<CreateBucketOutput, SdkError<CreateBucketError>> { let constraint = BucketLocationConstraint::from(region); let cfg = CreateBucketConfiguration::builder() .location_constraint(constraint) .build(); client .create_bucket() .create_bucket_configuration(cfg) .bucket(bucket_name) .send() .await }
  • Para obtener más información sobre la API, consulta CreateBucketla referencia sobre la API de AWS SDK para Rust.

SAP ABAP
SDK de SAP ABAP
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

TRY. lo_s3->createbucket( iv_bucket = iv_bucket_name ). MESSAGE 'S3 bucket created.' TYPE 'I'. CATCH /aws1/cx_s3_bucketalrdyexists. MESSAGE 'Bucket name already exists.' TYPE 'E'. CATCH /aws1/cx_s3_bktalrdyownedbyyou. MESSAGE 'Bucket already exists and is owned by you.' TYPE 'E'. ENDTRY.
  • Para obtener más información sobre la API, consulte CreateBucketla referencia sobre la API ABAP del AWS SDK para SAP.

Swift
SDK para Swift
nota

Esto es documentación preliminar para un SDK en versión preliminar. Está sujeta a cambios.

nota

Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

public func createBucket(name: String) async throws { let config = S3ClientTypes.CreateBucketConfiguration( locationConstraint: .usEast2 ) let input = CreateBucketInput( bucket: name, createBucketConfiguration: config ) _ = try await client.createBucket(input: input) }
  • Para obtener más información sobre la API, consulta CreateBucketla referencia sobre la API de AWS SDK for Swift.

nota

También puede utilizar un bucket de Amazon S3 desde una cuenta diferente, pero es posible que deba crear una política para el bucket que otorgue permisos de acceso a AWS Config. Para obtener más información sobre la concesión de permisos a un bucket de Amazon S3, consulte Permisos del bucket de Amazon S3 para el canal AWS Config de entrega y, a continuación, vaya a Creación de un tema de Amazon SNS.

Creación de un tema de Amazon SNS

Si ya tiene un tema de Amazon SNS en su cuenta y desea utilizarlo, omita este paso y vaya a Creación de un rol de IAM.

Para crear un tema de Amazon SNS
  1. Abra la consola de Amazon SNS en https://console.aws.amazon.com/sns/v3/home.

  2. Realice una de las siguientes acciones siguientes:

    • Si nunca se ha creado ningún tema bajo tu Cuenta de AWS dirección, lee la descripción de Amazon SNS en la página de inicio.

    • Si los temas se han creado Cuenta de AWS anteriormente bajo su dirección, en el panel de navegación, elija Temas.

  3. En la página Temas, elija Crear tema.

  4. En la página Crear tema, en la sección Detalles, haga lo siguiente:

    1. Para Tipo, elija un tipo de tema (estándar o FIFO).

    2. Ingrese un nombre para el nuevo tema. En el caso de un tema FIFO, agregue .fifo al final del nombre.

    3. (Opcional) Ingrese un nombre para mostrar para el tema.

    4. (Opcional) En el caso de un tema FIFO, puede elegir Desduplicación de mensajes basada en el contenido para habilitar la desduplicación de mensajes predeterminada. Para obtener más información, consulte Desduplicación de mensajes para temas FIFO.

  5. (Opcional) Expanda la sección Encryption (Cifrado) y haga lo siguiente. Para obtener más información, consulte Cifrado en reposo.

    1. Elija Habilitar el cifrado.

    2. Especifique la clave maestra del cliente (CMK). Para obtener más información, consulte Términos clave.

      Se muestran los valores de Description (Descripción), Account (Cuenta) y CMK ARN (ARN de CMK) de cada CMK.

      importante

      Si no es el propietario de la CMK o si ha iniciado sesión con una cuenta que no tiene los permisos kms:ListAliases y kms:DescribeKey, no podrá ver la información sobre la CMK en la consola de Amazon SNS.

      Pida al propietario de la CMK que le conceda estos permisos. Para obtener más información, consulte Permisos API de AWS KMS : referencia de recursos y acciones en la Guía para desarrolladores de AWS Key Management Service .

      • El alias/aws/sns de CMK AWS gestionado para Amazon SNS (predeterminado) está seleccionado de forma predeterminada.

        nota

        Tenga en cuenta lo siguiente:

        • La primera vez que utilice AWS Management Console para especificar la CMK AWS gestionada para Amazon SNS para un tema AWS KMS , crea AWS la CMK gestionada para Amazon SNS.

        • Como alternativa, la primera vez que utilice la Publish acción en un tema con SSE habilitado, se AWS KMS creará la CMK AWS gestionada para Amazon SNS.

      • Para usar una CMK personalizada suya Cuenta de AWS, elija el campo Clave maestra del cliente (CMK) y, a continuación, elija la CMK personalizada de la lista.

        nota

        Para obtener instrucciones acerca de cómo crear CMK personalizadas, consulte Creación de claves en laGuía para desarrolladores de AWS Key Management Service .

      • Para usar un ARN CMK personalizado de Cuenta de AWS su cuenta o de AWS otra, introdúzcalo en el campo Clave maestra del cliente (CMK).

  6. (Opcional) De forma predeterminada, solo el propietario del tema puede publicar en el tema o suscribirse a este. Para configurar permisos de acceso adicionales, expanda la sección Access policy (Política de acceso). Para obtener más información, consulte ¿Qué es Amazon SNS? y Ejemplos de casos de control de acceso con Amazon SNS.

    nota

    Cuando se crea un tema a través de la consola, la política predeterminada utiliza la clave de condición aws:SourceOwner. Esta clave es similar a aws:SourceAccount.

  7. (Opcional) Para configurar la forma en que Amazon SNS reintenta los intentos de entrega de mensajes con error, expanda la sección Política de reintentos de entrega (HTTP/S). Para obtener más información, consulte Reintento de entrega de mensajes de Amazon SNS.

  8. (Opcional) Para configurar la forma en que Amazon SNS registra la entrega de mensajes CloudWatch, amplíe la sección Registro del estado de entrega. Para obtener más información, consulte Estado de entrega de mensajes de Amazon SNS.

  9. (Opcional) Para añadir etiquetas de metadatos al tema, expanda la sección Tags (Etiquetas), escriba un valor en Key (Clave) y en Value (Valor) (opcional) y elija Add tag (Añadir etiqueta). Para obtener más información, consulte Etiquetado de temas de Amazon SNS.

  10. Elija Crear nuevo tema.

    Se crea el tema y se muestra la MyTopicpágina.

    El nombre del tema, el ARN, (opcional) el nombre para mostrar y el ID de la cuenta AWS del propietario del tema se muestran en la sección Detalles.

  11. Copie el ARN del tema en el portapapeles, por ejemplo:

    arn:aws:sns:us-east-2:123456789012:MyTopic
Para suscribir una dirección de correo electrónico al tema de Amazon SNS
  1. Abra la consola de Amazon SNS en https://console.aws.amazon.com/sns/v3/home.

  2. En el panel de navegación izquierdo, elija Suscripciones.

  3. En la página Subscriptions (Suscripciones), elija Create subscription (Crear suscripción).

  4. En la página Create subscription (Crear suscripción), en la sección Details (Detalles), haga lo siguiente:

    1. En ARN de tema, elija el nombre de recurso de Amazon (ARN) de un tema.

    2. En Protocolo, elija un tipo de punto de enlace. Los tipos de puntos de enlace disponibles son:

    3. En Punto de enlace, ingrese el valor del punto de enlace, como una dirección de correo electrónico o el ARN de una cola de Amazon SQS.

    4. Solo puntos finales de Firehose: en el ARN de la función de suscripción, especifique el ARN de la función de IAM que creó para escribir en las transmisiones de entrega de Firehose. Para obtener más información, consulte los temas sobre requisitos previos para suscribirse a las transmisiones de entrega de Firehose a Amazon SNS.

    5. (Opcional) Para los puntos de enlace Firehose, Amazon SQS y HTTP/S, también puede habilitar la entrega de mensajes sin procesar. Para obtener más información, consulte Entrega de mensajes sin procesar de Amazon SNS.

    6. (Opcional) Para configurar una política de filtro, expanda la sección Política de filtro de suscripción. Para obtener más información, consulte Políticas de filtro de suscripciones de Amazon SNS.

    7. (Opcional) Para configurar una cola de mensajes fallidos en la suscripción, expanda la sección Política de reconducción (cola de mensajes fallidos). Para obtener más información, consulte Colas de mensajes fallidos (DLQ) de Amazon SNS.

    8. Elija Crear una suscripción.

      En la consola se crea la suscripción y se abre la página Detalles de la suscripción.

Para usar un AWS SDK, debe configurarlo con sus credenciales. Para obtener más información, consulte Archivos de configuración y credenciales compartidos en la Guía de referencia de SDK y herramientas de AWS .

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

.NET
AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Cree un tema con un nombre específico.

using System; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// This example shows how to use Amazon Simple Notification Service /// (Amazon SNS) to add a new Amazon SNS topic. /// </summary> public class CreateSNSTopic { public static async Task Main() { string topicName = "ExampleSNSTopic"; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); var topicArn = await CreateSNSTopicAsync(client, topicName); Console.WriteLine($"New topic ARN: {topicArn}"); } /// <summary> /// Creates a new SNS topic using the supplied topic name. /// </summary> /// <param name="client">The initialized SNS client object used to /// create the new topic.</param> /// <param name="topicName">A string representing the topic name.</param> /// <returns>The Amazon Resource Name (ARN) of the created topic.</returns> public static async Task<string> CreateSNSTopicAsync(IAmazonSimpleNotificationService client, string topicName) { var request = new CreateTopicRequest { Name = topicName, }; var response = await client.CreateTopicAsync(request); return response.TopicArn; } }

Cree un tema nuevo con un nombre y atributos específicos de FIFO y desduplicación.

/// <summary> /// Create a new topic with a name and specific FIFO and de-duplication attributes. /// </summary> /// <param name="topicName">The name for the topic.</param> /// <param name="useFifoTopic">True to use a FIFO topic.</param> /// <param name="useContentBasedDeduplication">True to use content-based de-duplication.</param> /// <returns>The ARN of the new topic.</returns> public async Task<string> CreateTopicWithName(string topicName, bool useFifoTopic, bool useContentBasedDeduplication) { var createTopicRequest = new CreateTopicRequest() { Name = topicName, }; if (useFifoTopic) { // Update the name if it is not correct for a FIFO topic. if (!topicName.EndsWith(".fifo")) { createTopicRequest.Name = topicName + ".fifo"; } // Add the attributes from the method parameters. createTopicRequest.Attributes = new Dictionary<string, string> { { "FifoTopic", "true" } }; if (useContentBasedDeduplication) { createTopicRequest.Attributes.Add("ContentBasedDeduplication", "true"); } } var createResponse = await _amazonSNSClient.CreateTopicAsync(createTopicRequest); return createResponse.TopicArn; }
  • Para obtener más información sobre la API, consulta CreateTopicla Referencia AWS SDK for .NET de la API.

C++
SDK para C++
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

//! Create an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param topicName: An Amazon SNS topic name. \param topicARNResult: String to return the Amazon Resource Name (ARN) for the topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::createTopic(const Aws::String &topicName, Aws::String &topicARNResult, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::CreateTopicRequest request; request.SetName(topicName); const Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request); if (outcome.IsSuccess()) { topicARNResult = outcome.GetResult().GetTopicArn(); std::cout << "Successfully created an Amazon SNS topic " << topicName << " with topic ARN '" << topicARNResult << "'." << std::endl; } else { std::cerr << "Error creating topic " << topicName << ":" << outcome.GetError().GetMessage() << std::endl; topicARNResult.clear(); } return outcome.IsSuccess(); }
  • Para obtener más información sobre la API, consulta CreateTopicla Referencia AWS SDK for C++ de la API.

CLI
AWS CLI

Para crear un tema de SNS

En el siguiente ejemplo de create-topic se crea un tema de SNS denominado my-topic.

aws sns create-topic \ --name my-topic

Salida:

{ "ResponseMetadata": { "RequestId": "1469e8d7-1642-564e-b85d-a19b4b341f83" }, "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic" }

Para obtener más información, consulte Uso de la interfaz de línea de AWS comandos con Amazon SQS y Amazon SNS en la Guía del usuario de AWS la interfaz de línea de comandos.

  • Para obtener más información sobre la API, consulte la Referencia CreateTopicde AWS CLI comandos.

Go
SDK para Go V2
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // CreateTopic creates an Amazon SNS topic with the specified name. You can optionally // specify that the topic is created as a FIFO topic and whether it uses content-based // deduplication instead of ID-based deduplication. func (actor SnsActions) CreateTopic(topicName string, isFifoTopic bool, contentBasedDeduplication bool) (string, error) { var topicArn string topicAttributes := map[string]string{} if isFifoTopic { topicAttributes["FifoTopic"] = "true" } if contentBasedDeduplication { topicAttributes["ContentBasedDeduplication"] = "true" } topic, err := actor.SnsClient.CreateTopic(context.TODO(), &sns.CreateTopicInput{ Name: aws.String(topicName), Attributes: topicAttributes, }) if err != nil { log.Printf("Couldn't create topic %v. Here's why: %v\n", topicName, err) } else { topicArn = *topic.TopicArn } return topicArn, err }
  • Para obtener más información sobre la API, consulta CreateTopicla Referencia AWS SDK for Go de la API.

Java
SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateTopic { public static void main(String[] args) { final String usage = """ Usage: <topicName> Where: topicName - The name of the topic to create (for example, mytopic). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicName = args[0]; System.out.println("Creating a topic with name: " + topicName); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnVal = createSNSTopic(snsClient, topicName); System.out.println("The topic ARN is" + arnVal); snsClient.close(); } public static String createSNSTopic(SnsClient snsClient, String topicName) { CreateTopicResponse result; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • Para obtener más información sobre la API, consulta CreateTopicla Referencia AWS SDK for Java 2.x de la API.

JavaScript
SDK para JavaScript (v3)
nota

Hay más información. GitHub Busque el ejemplo completo y aprenda a configurarlo y ejecutarlo en el Repositorio de ejemplos de código de AWS.

Cree el cliente en un módulo separado y expórtelo.

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

Importe el SDK y los módulos de cliente, y llame a la API.

import { CreateTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicName - The name of the topic to create. */ export const createTopic = async (topicName = "TOPIC_NAME") => { const response = await snsClient.send( new CreateTopicCommand({ Name: topicName }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME' // } return response; };
Kotlin
SDK para Kotlin
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

suspend fun createSNSTopic(topicName: String): String { val request = CreateTopicRequest { name = topicName } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.createTopic(request) return result.topicArn.toString() } }
  • Para obtener más información sobre la API, consulta CreateTopicla referencia sobre el AWS SDK para la API de Kotlin.

PHP
SDK para PHP
nota

Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Create a Simple Notification Service topics in your AWS account at the requested region. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $topicname = 'myTopic'; try { $result = $SnSclient->createTopic([ 'Name' => $topicname, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
Python
SDK para Python (Boto3)
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def create_topic(self, name): """ Creates a notification topic. :param name: The name of the topic to create. :return: The newly created topic. """ try: topic = self.sns_resource.create_topic(Name=name) logger.info("Created topic %s with ARN %s.", name, topic.arn) except ClientError: logger.exception("Couldn't create topic %s.", name) raise else: return topic
  • Para obtener más información sobre la API, consulta CreateTopicla AWS Referencia de API de SDK for Python (Boto3).

Ruby
SDK para Ruby
nota

Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

# This class demonstrates how to create an Amazon Simple Notification Service (SNS) topic. class SNSTopicCreator # Initializes an SNS client. # # Utilizes the default AWS configuration for region and credentials. def initialize @sns_client = Aws::SNS::Client.new end # Attempts to create an SNS topic with the specified name. # # @param topic_name [String] The name of the SNS topic to create. # @return [Boolean] true if the topic was successfully created, false otherwise. def create_topic(topic_name) @sns_client.create_topic(name: topic_name) puts "The topic '#{topic_name}' was successfully created." true rescue Aws::SNS::Errors::ServiceError => e # Handles SNS service errors gracefully. puts "Error while creating the topic named '#{topic_name}': #{e.message}" false end end # Example usage: if $PROGRAM_NAME == __FILE__ topic_name = "YourTopicName" # Replace with your topic name sns_topic_creator = SNSTopicCreator.new puts "Creating the topic '#{topic_name}'..." unless sns_topic_creator.create_topic(topic_name) puts "The topic was not created. Stopping program." exit 1 end end
Rust
SDK para Rust
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

async fn make_topic(client: &Client, topic_name: &str) -> Result<(), Error> { let resp = client.create_topic().name(topic_name).send().await?; println!( "Created topic with ARN: {}", resp.topic_arn().unwrap_or_default() ); Ok(()) }
  • Para obtener más información sobre la API, consulta CreateTopicla referencia sobre la API de AWS SDK para Rust.

SAP ABAP
SDK de SAP ABAP
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

TRY. oo_result = lo_sns->createtopic( iv_name = iv_topic_name ). " oo_result is returned for testing purposes. " MESSAGE 'SNS topic created' TYPE 'I'. CATCH /aws1/cx_snstopiclimitexcdex. MESSAGE 'Unable to create more topics. You have reached the maximum number of topics allowed.' TYPE 'E'. ENDTRY.
  • Para obtener más información sobre la API, consulte CreateTopicla referencia sobre la API ABAP del AWS SDK para SAP.

nota

También puede utilizar un tema de Amazon SNS de otra cuenta, pero es posible que tenga que crear una política para el tema que conceda permisos de acceso a AWS Config. Para obtener información sobre la concesión de permisos a un tema de Amazon SNS, consulte Permisos para el tema de Amazon SNS y, a continuación, vaya a Creación de un rol de IAM.

Creación de un rol de IAM

Puede usar la consola de IAM para crear un rol de IAM que conceda AWS Config permisos para acceder a su bucket de Amazon S3, acceder a su tema de Amazon SNS y obtener detalles de configuración de los recursos compatibles. AWS Al utilizar la consola para crear un rol de IAM, AWS Config asocia automáticamente los permisos necesarios al rol en su nombre.

nota

Si ha utilizado un AWS servicio que utiliza AWS Config (como AWS Security Hub o AWS Control Tower) y ya se ha creado un AWS Config rol, debe asegurarse de que el rol de IAM que utilice al configurar AWS Config mantenga los mismos privilegios mínimos que el AWS Config rol ya creado para que el otro AWS servicio siga ejecutándose según lo previsto.

Por ejemplo, si AWS Control Tower tiene una función de IAM que AWS Config permite leer los objetos de Amazon S3, debe garantizar que se concedan los mismos permisos en la función de IAM que utilizó al configurar. AWS Config De lo contrario, podría interferir con las operaciones AWS de Control Tower.

Para obtener más información sobre las funciones de IAM AWS Config, consulte AWS Identity and Access Management.

Para crear un rol para un servicio AWS
  1. Inicie sesión en la consola de IAM AWS Management Console y ábrala en https://console.aws.amazon.com/iam/.

  2. En el panel de navegación de la consola de IAM, seleccione Roles y, a continuación, elija Crear rol.

  3. En Select trusted entity (Seleccionar entidad de confianza), elija AWS service (Servicio de ).

  4. Elige el caso de uso que desees para AWS Config: Config - Customizable, Config - Organizations, Config o Config - Conformance Packs. A continuación, elija Siguiente.

  5. En la página Asignar nombre, revisar y crear, revise los datos de su rol y elija Crear rol.

Para usar un AWS SDK, debe configurarlo con sus credenciales. Para obtener más información, consulte Archivos de configuración y credenciales compartidos en la Guía de referencia de SDK y herramientas de AWS .

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

.NET
AWS SDK for .NET
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

/// <summary> /// Create a new IAM role. /// </summary> /// <param name="roleName">The name of the IAM role.</param> /// <param name="rolePolicyDocument">The name of the IAM policy document /// for the new role.</param> /// <returns>The Amazon Resource Name (ARN) of the role.</returns> public async Task<string> CreateRoleAsync(string roleName, string rolePolicyDocument) { var request = new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = rolePolicyDocument, }; var response = await _IAMService.CreateRoleAsync(request); return response.Role.Arn; }
  • Para obtener más información sobre la API, consulta CreateRolela Referencia AWS SDK for .NET de la API.

Bash
AWS CLI con el script Bash
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.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function iam_create_role # # This function creates an IAM role. # # Parameters: # -n role_name -- The name of the IAM role. # -p policy_json -- The assume role policy document. # # Returns: # The ARN of the role. # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function iam_create_role() { local role_name policy_document response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function iam_create_user_access_key" echo "Creates an AWS Identity and Access Management (IAM) role." echo " -n role_name The name of the IAM role." echo " -p policy_json -- The assume role policy document." echo "" } # Retrieve the calling parameters. while getopts "n:p:h" option; do case "${option}" in n) role_name="${OPTARG}" ;; p) policy_document="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$role_name" ]]; then errecho "ERROR: You must provide a role name with the -n parameter." usage return 1 fi if [[ -z "$policy_document" ]]; then errecho "ERROR: You must provide a policy document with the -p parameter." usage return 1 fi response=$(aws iam create-role \ --role-name "$role_name" \ --assume-role-policy-document "$policy_document" \ --output text \ --query Role.Arn) local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports create-role operation failed.\n$response" return 1 fi echo "$response" return 0 }
  • Para obtener más información sobre la API, consulta CreateRolela Referencia de AWS CLI comandos.

C++
SDK para C++
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

bool AwsDoc::IAM::createIamRole( const Aws::String &roleName, const Aws::String &policy, const Aws::Client::ClientConfiguration &clientConfig) { Aws::IAM::IAMClient client(clientConfig); Aws::IAM::Model::CreateRoleRequest request; request.SetRoleName(roleName); request.SetAssumeRolePolicyDocument(policy); Aws::IAM::Model::CreateRoleOutcome outcome = client.CreateRole(request); if (!outcome.IsSuccess()) { std::cerr << "Error creating role. " << outcome.GetError().GetMessage() << std::endl; } else { const Aws::IAM::Model::Role iamRole = outcome.GetResult().GetRole(); std::cout << "Created role " << iamRole.GetRoleName() << "\n"; std::cout << "ID: " << iamRole.GetRoleId() << "\n"; std::cout << "ARN: " << iamRole.GetArn() << std::endl; } return outcome.IsSuccess(); }
  • Para obtener más información sobre la API, consulta CreateRolela Referencia AWS SDK for C++ de la API.

CLI
AWS CLI

Ejemplo 1: cómo crear un rol de IAM

El siguiente comando create-role crean un rol denominado Test-Role y le asocia una política de confianza.

aws iam create-role \ --role-name Test-Role \ --assume-role-policy-document file://Test-Role-Trust-Policy.json

Salida:

{ "Role": { "AssumeRolePolicyDocument": "<URL-encoded-JSON>", "RoleId": "AKIAIOSFODNN7EXAMPLE", "CreateDate": "2013-06-07T20:43:32.821Z", "RoleName": "Test-Role", "Path": "/", "Arn": "arn:aws:iam::123456789012:role/Test-Role" } }

La política de confianza se define como un documento JSON en el archivo Test-Role-Trust-Policy.json. (El nombre y la extensión del archivo no son significativos). La política de confianza debe especificar una entidad principal.

Utilice el comando put-role-policy para asociar una política de permisos a un rol.

Para más información, consulte Creación de roles de IAM en la Guía del usuario de IAM de AWS .

Ejemplo 2: cómo crear un rol de IAM con una duración máxima de sesión especificada

El siguiente comando create-role crea un rol denominado Test-Role y establece una duración máxima de sesión de 7200 segundos (2 horas).

aws iam create-role \ --role-name Test-Role \ --assume-role-policy-document file://Test-Role-Trust-Policy.json \ --max-session-duration 7200

Salida:

{ "Role": { "Path": "/", "RoleName": "Test-Role", "RoleId": "AKIAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::12345678012:role/Test-Role", "CreateDate": "2023-05-24T23:50:25+00:00", "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::12345678012:root" }, "Action": "sts:AssumeRole" } ] } } }

Para obtener más información, consulte Modificación de la duración máxima de sesión (AWS API) de un rol en la Guía del usuario de AWS IAM.

Ejemplo 3: cómo crear un rol de IAM con etiquetas

El siguiente comando crea un rol de IAM Test-Role con etiquetas. En este ejemplo, se utiliza el indicador de parámetro --tags con las siguientes etiquetas con formato JSON: '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'. Alternativamente, el indicador --tags se puede usar con etiquetas en formato abreviado: 'Key=Department,Value=Accounting Key=Location,Value=Seattle'.

aws iam create-role \ --role-name Test-Role \ --assume-role-policy-document file://Test-Role-Trust-Policy.json \ --tags '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'

Salida:

{ "Role": { "Path": "/", "RoleName": "Test-Role", "RoleId": "AKIAIOSFODNN7EXAMPLE", "Arn": "arn:aws:iam::123456789012:role/Test-Role", "CreateDate": "2023-05-25T23:29:41+00:00", "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:root" }, "Action": "sts:AssumeRole" } ] }, "Tags": [ { "Key": "Department", "Value": "Accounting" }, { "Key": "Location", "Value": "Seattle" } ] } }

Para obtener más información, consulte Etiquetado de roles de IAM en la Guía del usuario de AWS IAM.

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

Go
SDK para Go V2
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions // used in the examples. // It contains an IAM service client that is used to perform role actions. type RoleWrapper struct { IamClient *iam.Client } // CreateRole creates a role that trusts a specified user. The trusted user can assume // the role to acquire its permissions. // PolicyDocument shows how to work with a policy document as a data structure and // serialize it to JSON by using Go's JSON marshaler. func (wrapper RoleWrapper) CreateRole(roleName string, trustedUserArn string) (*types.Role, error) { var role *types.Role trustPolicy := PolicyDocument{ Version: "2012-10-17", Statement: []PolicyStatement{{ Effect: "Allow", Principal: map[string]string{"AWS": trustedUserArn}, Action: []string{"sts:AssumeRole"}, }}, } policyBytes, err := json.Marshal(trustPolicy) if err != nil { log.Printf("Couldn't create trust policy for %v. Here's why: %v\n", trustedUserArn, err) return nil, err } result, err := wrapper.IamClient.CreateRole(context.TODO(), &iam.CreateRoleInput{ AssumeRolePolicyDocument: aws.String(string(policyBytes)), RoleName: aws.String(roleName), }) if err != nil { log.Printf("Couldn't create role %v. Here's why: %v\n", roleName, err) } else { role = result.Role } return role, err }
  • Para obtener más información sobre la API, consulta CreateRolela Referencia AWS SDK for Go de la API.

Java
SDK para Java 2.x
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import software.amazon.awssdk.services.iam.model.CreateRoleRequest; import software.amazon.awssdk.services.iam.model.CreateRoleResponse; import software.amazon.awssdk.services.iam.model.IamException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; import java.io.FileReader; /* * This example requires a trust policy document. For more information, see: * https://aws.amazon.com/blogs/security/how-to-use-trust-policies-with-iam-roles/ * * * In addition, set up your development environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateRole { public static void main(String[] args) throws Exception { final String usage = """ Usage: <rolename> <fileLocation>\s Where: rolename - The name of the role to create.\s fileLocation - The location of the JSON document that represents the trust policy.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String rolename = args[0]; String fileLocation = args[1]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); String result = createIAMRole(iam, rolename, fileLocation); System.out.println("Successfully created user: " + result); iam.close(); } public static String createIAMRole(IamClient iam, String rolename, String fileLocation) throws Exception { try { JSONObject jsonObject = (JSONObject) readJsonSimpleDemo(fileLocation); CreateRoleRequest request = CreateRoleRequest.builder() .roleName(rolename) .assumeRolePolicyDocument(jsonObject.toJSONString()) .description("Created using the AWS SDK for Java") .build(); CreateRoleResponse response = iam.createRole(request); System.out.println("The ARN of the role is " + response.role().arn()); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static Object readJsonSimpleDemo(String filename) throws Exception { FileReader reader = new FileReader(filename); JSONParser jsonParser = new JSONParser(); return jsonParser.parse(reader); } }
  • Para obtener más información sobre la API, consulta CreateRolela Referencia AWS SDK for Java 2.x de la API.

JavaScript
SDK para JavaScript (v3)
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.

Cree el rol.

import { CreateRoleCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} roleName */ export const createRole = (roleName) => { const command = new CreateRoleCommand({ AssumeRolePolicyDocument: JSON.stringify({ Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { Service: "lambda.amazonaws.com", }, Action: "sts:AssumeRole", }, ], }), RoleName: roleName, }); return client.send(command); };
  • Para obtener más información sobre la API, consulta CreateRolela Referencia AWS SDK for JavaScript de la API.

PHP
SDK para PHP
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

$uuid = uniqid(); $service = new IAMService(); $assumeRolePolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [{ \"Effect\": \"Allow\", \"Principal\": {\"AWS\": \"{$user['Arn']}\"}, \"Action\": \"sts:AssumeRole\" }] }"; $assumeRoleRole = $service->createRole("iam_demo_role_$uuid", $assumeRolePolicyDocument); echo "Created role: {$assumeRoleRole['RoleName']}\n"; /** * @param string $roleName * @param string $rolePolicyDocument * @return array * @throws AwsException */ public function createRole(string $roleName, string $rolePolicyDocument) { $result = $this->customWaiter(function () use ($roleName, $rolePolicyDocument) { return $this->iamClient->createRole([ 'AssumeRolePolicyDocument' => $rolePolicyDocument, 'RoleName' => $roleName, ]); }); return $result['Role']; }
  • Para obtener más información sobre la API, consulta CreateRolela Referencia AWS SDK for PHP de la API.

PowerShell
Herramientas para PowerShell

Ejemplo 1: en este ejemplo se crea un nuevo rol con el nombre MyNewRole y se le adjunta la política que se encuentra en el archivo NewRoleTrustPolicy.json. Tenga en cuenta que debe usar el parámetro de conmutación -Raw para procesar correctamente el archivo de políticas JSON. El documento de política que se muestra en el resultado tiene codificación de URL. En este ejemplo, se decodifica con el método UrlDecode de .NET.

$results = New-IAMRole -AssumeRolePolicyDocument (Get-Content -raw NewRoleTrustPolicy.json) -RoleName MyNewRole $results

Salida:

Arn : arn:aws:iam::123456789012:role/MyNewRole AssumeRolePolicyDocument : %7B%0D%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0D%0A%20%20%22Statement%22 %3A%20%5B%0D%0A%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%22Sid%22%3A%20%22%22%2C %0D%0A%20%20%20%20%20%20%22Effect%22%3A%20%22Allow%22%2C%0D%0A%20%20%20%20%20%20 %22Principal%22%3A%20%7B%0D%0A%20%20%20%20%20%20%20%20%22AWS%22%3A%20%22arn%3Aaws %3Aiam%3A%3A123456789012%3ADavid%22%0D%0A%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20 %20%20%20%22Action%22%3A%20%22sts%3AAssumeRole%22%0D%0A%20%20%20%20%7D%0D%0A%20 %20%5D%0D%0A%7D CreateDate : 4/15/2015 11:04:23 AM Path : / RoleId : V5PAJI2KPN4EAEXAMPLE1 RoleName : MyNewRole [System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility") [System.Web.HttpUtility]::UrlDecode($results.AssumeRolePolicyDocument) { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::123456789012:David" }, "Action": "sts:AssumeRole" } ] }
  • Para obtener más información sobre la API, consulte CreateRolela referencia de AWS Tools for PowerShell cmdlets.

Python
SDK para Python (Boto3)
nota

Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

def create_role(role_name, allowed_services): """ Creates a role that lets a list of specified services assume the role. :param role_name: The name of the role. :param allowed_services: The services that can assume the role. :return: The newly created role. """ trust_policy = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"Service": service}, "Action": "sts:AssumeRole", } for service in allowed_services ], } try: role = iam.create_role( RoleName=role_name, AssumeRolePolicyDocument=json.dumps(trust_policy) ) logger.info("Created role %s.", role.name) except ClientError: logger.exception("Couldn't create role %s.", role_name) raise else: return role
  • Para obtener más información sobre la API, consulta CreateRolela AWS Referencia de API de SDK for Python (Boto3).

Ruby
SDK para Ruby
nota

Hay más información al respecto. GitHub Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

# Creates a role and attaches policies to it. # # @param role_name [String] The name of the role. # @param assume_role_policy_document [Hash] The trust relationship policy document. # @param policy_arns [Array<String>] The ARNs of the policies to attach. # @return [String, nil] The ARN of the new role if successful, or nil if an error occurred. def create_role(role_name, assume_role_policy_document, policy_arns) response = @iam_client.create_role( role_name: role_name, assume_role_policy_document: assume_role_policy_document.to_json ) role_arn = response.role.arn policy_arns.each do |policy_arn| @iam_client.attach_role_policy( role_name: role_name, policy_arn: policy_arn ) end role_arn rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating role: #{e.message}") nil end
  • Para obtener más información sobre la API, consulta CreateRolela Referencia AWS SDK for Ruby de la API.

Rust
SDK para Rust
nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

pub async fn create_role( client: &iamClient, role_name: &str, role_policy_document: &str, ) -> Result<Role, iamError> { let response: CreateRoleOutput = loop { if let Ok(response) = client .create_role() .role_name(role_name) .assume_role_policy_document(role_policy_document) .send() .await { break response; } }; Ok(response.role.unwrap()) }
  • Para obtener más información sobre la API, consulta CreateRolela referencia sobre la API de AWS SDK para Rust.

Swift
SDK para Swift
nota

Esto es documentación preliminar para un SDK en versión preliminar. Está sujeta a cambios.

nota

Hay más información al respecto GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

public func createRole(name: String, policyDocument: String) async throws -> String { let input = CreateRoleInput( assumeRolePolicyDocument: policyDocument, roleName: name ) do { let output = try await client.createRole(input: input) guard let role = output.role else { throw ServiceHandlerError.noSuchRole } guard let id = role.roleId else { throw ServiceHandlerError.noSuchRole } return id } catch { throw error } }
  • Para obtener más información sobre la API, consulta CreateRolela referencia sobre la API de AWS SDK for Swift.