Prerequisites - Amazon Config
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China.

Prerequisites

Before setting up Amazon with the Amazon CLI, you need to create an Amazon S3 bucket, an Amazon SNS topic, and an IAM role with attached policies as prerequisites. You can then use the Amazon CLI to specify the bucket, topic, and role for Amazon Config. Follow this procedure to set up your prerequisites for Amazon Config.

Creating an Amazon S3 Bucket

If you already have an Amazon S3 bucket in your account and want to use it, skip this step and go to Creating an Amazon SNS Topic.

To create a bucket

  1. Open the Amazon S3 console at https://console.amazonaws.cn/s3/.

  2. Choose Create bucket.

  3. In Bucket name, enter a DNS-compliant name for your bucket.

    The bucket name must:

    • Be unique across all of Amazon S3.

    • Be between 3 and 63 characters long.

    • Not contain uppercase characters.

    • Start with a lowercase letter or number.

    After you create the bucket, you can't change its name. Make sure the bucket name you choose is unique across all existing bucket names in Amazon S3. For more information on bucket naming rules and conventions, see Bucket restrictions and Limitations in the Amazon Simple Storage Service User Guide.

    Important

    Avoid including sensitive information, such as account numbers, in the bucket name. The bucket name is visible in the URLs that point to the objects in the bucket.

  4. In Region, choose the Amazon Region where you want the bucket to reside.

    Choose a Region close to you to minimize latency and costs and address regulatory requirements. Objects stored in a Region never leave that Region unless you explicitly transfer them to another Region. For a list of Amazon S3 Amazon Regions, see Amazon service endpoints in the Amazon Web Services General Reference.

  5. In Bucket settings for Block Public Access, choose the Block Public Access settings that you want to apply to the bucket.

    We recommend that you leave all settings enabled unless you know you need to turn one or more of them off for your use case, such as to host a public website. Block public access settings that you enable for the bucket will also be enabled for all access points that you create on the bucket. For more information about blocking public access, see Using Amazon S3 Block Public Access in the Amazon Simple Storage Service User Guide.

  6. (Optional) If you want to enable S3 Object Lock:

    1. Choose Advanced settings, and read the message that appears.

      Important

      You can only enable S3 Object Lock for a bucket when you create it. If you enable Object Lock for the bucket, you can't disable it later. Enabling Object Lock also enables versioning for the bucket. After you enable Object Lock for the bucket, you must configure the Object Lock settings before any objects in the bucket will be protected. For more information about configuring protection for objects, see Configuring S3 Object Lock using the Amazon S3 console.

    2. If you want to enable Object Lock, enter enable in the text box and choose Confirm.

    For more information about the S3 Object Lock feature, see Locking Objects Using Amazon S3 Object Lock in the Amazon Simple Storage Service User Guide.

  7. Choose Create bucket.

When you use the Amazon SDKs to create a bucket, you must create a client and then use the client to send a request to create a bucket. As a best practice, you should create your client and bucket in the same Amazon Web Services Region. If you don't specify a Region when you create a client or a bucket, Amazon S3 uses the default Region US East (N. Virginia).

To create a client to access a dual-stack endpoint, you must specify an Amazon Web Services Region. For more information, see Amazon S3 dual-stack endpoints. For a list of available Amazon Web Services Regions, see Regions and endpoints in the Amazon General Reference.

When you create a client, the Region maps to the Region-specific endpoint. The client uses this endpoint to communicate with Amazon S3: s3.<region>.amazonaws.com.cn. If your Region launched after March 20, 2019, your client and bucket must be in the same Region. However, you can use a client in the US East (N. Virginia) Region to create a bucket in any Region that launched before March 20, 2019. For more information, see Legacy Endpoints.

These Amazon SDK code examples perform the following tasks:

  • Create a client by explicitly specifying an Amazon Web Services Region — In the example, the client uses the s3.us-west-2.amazonaws.com.cn endpoint to communicate with Amazon S3. You can specify any Amazon Web Services Region. For a list of Amazon Web Services Regions, see Regions and endpoints in the Amazon General Reference.

  • Send a create bucket request by specifying only a bucket name — The client sends a request to Amazon S3 to create the bucket in the Region where you created a client.

  • Retrieve information about the location of the bucket — Amazon S3 stores bucket location information in the location subresource that is associated with the bucket.

Java

This example shows how to create an Amazon S3 bucket using the Amazon SDK for Java. For instructions on creating and testing a working sample, see Testing the Amazon S3 Java Code Examples.

import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.CreateBucketRequest; import com.amazonaws.services.s3.model.GetBucketLocationRequest; import java.io.IOException; public class CreateBucket2 { public static void main(String[] args) throws IOException { Regions clientRegion = Regions.DEFAULT_REGION; String bucketName = "*** Bucket name ***"; try { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new ProfileCredentialsProvider()) .withRegion(clientRegion) .build(); if (!s3Client.doesBucketExistV2(bucketName)) { // Because the CreateBucketRequest object doesn't specify a region, the // bucket is created in the region specified in the client. s3Client.createBucket(new CreateBucketRequest(bucketName)); // Verify that the bucket was created by retrieving it and checking its location. String bucketLocation = s3Client.getBucketLocation(new GetBucketLocationRequest(bucketName)); System.out.println("Bucket location: " + bucketLocation); } } catch (AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it and returned an error response. e.printStackTrace(); } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } }
.NET

For information about how to create and test a working sample, see Running the Amazon S3 .NET Code Examples.

using Amazon; using Amazon.S3; using Amazon.S3.Model; using Amazon.S3.Util; using System; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { class CreateBucketTest { private const string bucketName = "*** bucket name ***"; // Specify your bucket region (an example region is shown). private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2; private static IAmazonS3 s3Client; public static void Main() { s3Client = new AmazonS3Client(bucketRegion); CreateBucketAsync().Wait(); } static async Task CreateBucketAsync() { try { if (!(await AmazonS3Util.DoesS3BucketExistAsync(s3Client, bucketName))) { var putBucketRequest = new PutBucketRequest { BucketName = bucketName, UseClientRegion = true }; PutBucketResponse putBucketResponse = await s3Client.PutBucketAsync(putBucketRequest); } // Retrieve the bucket location. string bucketLocation = await FindBucketLocationAsync(s3Client); } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } } static async Task<string> FindBucketLocationAsync(IAmazonS3 client) { string bucketLocation; var request = new GetBucketLocationRequest() { BucketName = bucketName }; GetBucketLocationResponse response = await client.GetBucketLocationAsync(request); bucketLocation = response.Location.ToString(); return bucketLocation; } } }
Ruby

For information about how to create and test a working sample, see Using the Amazon SDK for Ruby - Version 3.

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 it's 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 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__

You can also use the Amazon Command Line Interface (Amazon CLI) to create an S3 bucket. For more information, see create-bucket in the Amazon CLI Command Reference.

For information about the Amazon CLI, see What is the Amazon Command Line Interface? in the Amazon Command Line Interface User Guide.

Note

You can also use an Amazon S3 bucket from a different account, but you may need to create a policy for the bucket that grants access permissions to Amazon Config. For information on granting permissions to an Amazon S3 bucket, see Permissions for the Amazon S3 Bucket, and then go to Creating an Amazon SNS Topic.

Creating an Amazon SNS Topic

If you already have an Amazon SNS topic in your account and want to use it, skip this step and go to Creating an IAM Role.

To create an Amazon SNS topic

  1. Open the Amazon SNS console at https://console.amazonaws.cn/sns/v3/home.

  2. Do one of the following:

    • If no topics have ever been created under your Amazon Web Services account before, read the description of Amazon SNS on the home page.

    • If topics have been created under your Amazon Web Services account before, on the navigation panel, choose Topics.

  3. On the Topics page, choose Create topic.

  4. On the Create topic page, in the Details section, do the following:

    1. For Type, choose a topic type (Standard or FIFO).

    2. Enter a Name for the topic. For a FIFO topic, add .fifo to the end of the name.

    3. (Optional) Enter a Display name for the topic.

    4. (Optional) For a FIFO topic, you can choose content-based message deduplication to enable default message deduplication. For more information, see Message deduplication for FIFO topics.

  5. (Optional) Expand the Encryption section and do the following. For more information, see Encryption at rest.

    1. Choose Enable encryption.

    2. Specify the customer master key (CMK). For more information, see Key terms.

      For each CMK type, the Description, Account, and CMK ARN are displayed.

      Important

      If you aren't the owner of the CMK, or if you log in with an account that doesn't have the kms:ListAliases and kms:DescribeKey permissions, you won't be able to view information about the CMK on the Amazon SNS console.

      Ask the owner of the CMK to grant you these permissions. For more information, see the Amazon KMS API Permissions: Actions and Resources Reference in the Amazon Key Management Service Developer Guide.

      • The Amazon managed CMK for Amazon SNS (Default) alias/aws/sns is selected by default.

        Note

        Keep the following in mind:

        • The first time you use the Amazon Web Services Management Console to specify the Amazon managed CMK for Amazon SNS for a topic, Amazon KMS creates the Amazon managed CMK for Amazon SNS.

        • Alternatively, the first time you use the Publish action on a topic with SSE enabled, Amazon KMS creates the Amazon managed CMK for Amazon SNS.

      • To use a custom CMK from your Amazon account, choose the Customer master key (CMK) field and then choose the custom CMK from the list.

        Note

        For instructions on creating custom CMKs, see Creating Keys in the Amazon Key Management Service Developer Guide

      • To use a custom CMK ARN from your Amazon account or from another Amazon account, enter it into the Customer master key (CMK) field.

  6. (Optional) By default, only the topic owner can publish or subscribe to the topic. To configure additional access permissions, expand the Access policy section. For more information, see Identity and access management in Amazon SNS and Example cases for Amazon SNS access control.

    Note

    When you create a topic using the console, the default policy uses the aws:SourceOwner condition key. This key is similar to aws:SourceAccount.

  7. (Optional) To configure how Amazon SNS retries failed message delivery attempts, expand the Delivery retry policy (HTTP/S) section. For more information, see Amazon SNS message delivery retries.

  8. (Optional) To configure how Amazon SNS logs the delivery of messages to CloudWatch, expand the Delivery status logging section. For more information, see Amazon SNS message delivery status.

  9. (Optional) To add metadata tags to the topic, expand the Tags section, enter a Key and a Value (optional) and choose Add tag. For more information, see Amazon SNS topic tagging.

  10. Choose Create topic.

    The topic is created and the MyTopic page is displayed.

    The topic's Name, ARN, (optional) Display name, and Topic owner's Amazon account ID are displayed in the Details section.

  11. Copy the topic ARN to the clipboard, for example:

    arn:aws:sns:us-west-2:123456789012:MyTopic

To subscribe an email address to the Amazon SNS topic

  1. Open the Amazon SNS console at https://console.amazonaws.cn/sns/v3/home.

  2. In the left navigation pane, choose Subscriptions.

  3. On the Subscriptions page, choose Create subscription.

  4. On the Create subscription page, in the Details section, do the following:

    1. For Topic ARN, choose the Amazon Resource Name (ARN) of a topic.

    2. For Protocol, choose an endpoint type. The available endpoint types are:

    3. For Endpoint, enter the endpoint value, such as an email address or the ARN of an Amazon SQS queue.

    4. Kinesis Data Firehose endpoints only: For Subscription role ARN, specify the ARN of the IAM role that you created for writing to Kinesis Data Firehose delivery streams. For more information, see Prerequisites for subscribing Kinesis Data Firehose delivery streams to Amazon SNS topics.

    5. (Optional) For Kinesis Data Firehose, Amazon SQS, HTTP/S endpoints, you can also enable raw message delivery. For more information, see Amazon SNS raw message delivery.

    6. (Optional) To configure a filter policy, expand the Subscription filter policy section. For more information, see Amazon SNS subscription filter policies.

    7. (Optional) To configure a dead-letter queue for the subscription, expand the Redrive policy (dead-letter queue) section. For more information, see Amazon SNS dead-letter queues (DLQs).

    8. Choose Create subscription.

      The console creates the subscription and opens the subscription's Details page.

To use an Amazon SDK, you must configure it with your credentials. For more information, see The shared config and credentials files in the Amazon SDKs and Tools Reference Guide.

The following code examples show how to create an Amazon SNS topic.

.NET
Amazon SDK for .NET
Tip

To learn how to set up and run this example, see GitHub.

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. The example was created /// using the AWS SDK for .NET version 3.7 and .NET Core 5.0. /// </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; } }
  • For API details, see CreateTopic in Amazon SDK for .NET API Reference.

C++
SDK for C++
Tip

To learn how to set up and run this example, see GitHub.

Aws::SDKOptions options; Aws::InitAPI(options); { Aws::String topic_name = argv[1]; Aws::SNS::SNSClient sns; Aws::SNS::Model::CreateTopicRequest ct_req; ct_req.SetName(topic_name); auto ct_out = sns.CreateTopic(ct_req); if (ct_out.IsSuccess()) { std::cout << "Successfully created topic " << topic_name << std::endl; } else { std::cout << "Error creating topic " << topic_name << ":" << ct_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options);
  • For API details, see CreateTopic in Amazon SDK for C++ API Reference.

Go
SDK for Go V2
Tip

To learn how to set up and run this example, see GitHub.

  • For API details, see CreateTopic in Amazon SDK for Go API Reference.

Java
SDK for Java 2.x
Tip

To learn how to set up and run this example, see GitHub.

public static String createSNSTopic(SnsClient snsClient, String topicName ) { CreateTopicResponse result = null; 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 ""; }
  • For API details, see CreateTopic in Amazon SDK for Java 2.x API Reference.

JavaScript
SDK for JavaScript V3
Tip

To learn how to set up and run this example, see GitHub.

Create the client in a separate module and export it.

import { SNSClient } from "@aws-sdk/client-sns"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SNS service object. const snsClient = new SNSClient({ region: REGION }); export { snsClient };

Import the SDK and client modules and call the API.

// Import required AWS SDK clients and commands for Node.js import {CreateTopicCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters const params = { Name: "TOPIC_NAME" }; //TOPIC_NAME const run = async () => { try { const data = await snsClient.send(new CreateTopicCommand(params)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();
Kotlin
SDK for Kotlin
Note

This is prerelease documentation for a feature in preview release. It is subject to change.

Tip

To learn how to set up and run this example, see GitHub.

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() } }
  • For API details, see CreateTopic in Amazon SDK for Kotlin API reference.

PHP
SDK for PHP
Tip

To learn how to set up and run this example, see GitHub.

require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * 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 for Python (Boto3)
Tip

To learn how to set up and run this example, see GitHub.

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
  • For API details, see CreateTopic in Amazon SDK for Python (Boto3) API Reference.

Ruby
SDK for Ruby
Tip

To learn how to set up and run this example, see GitHub.

require 'aws-sdk-sns' # v2: require 'aws-sdk' def topic_created?(sns_client, topic_name) sns_client.create_topic(name: topic_name) rescue StandardError => e puts "Error while creating the topic named '#{topic_name}': #{e.message}" end # Full example call: def run_me topic_name = 'TOPIC_NAME' region = 'REGION' sns_client = Aws::SNS::Client.new(region: region) puts "Creating the topic '#{topic_name}'..." if topic_created?(sns_client, topic_name) puts 'The topic was created.' else puts 'The topic was not created. Stopping program.' exit 1 end end run_me if $PROGRAM_NAME == __FILE__
Rust
SDK for Rust
Note

This documentation is for an SDK in preview release. The SDK is subject to change and should not be used in production.

Tip

To learn how to set up and run this example, see GitHub.

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(()) }
  • For API details, see CreateTopic in Amazon SDK for Rust API reference.

You can also use the Amazon Command Line Interface (Amazon CLI) to create an an Amazon SNS topic. For more information, see create-topic in the Amazon CLI Command Reference.

For information about the Amazon CLI, see What is the Amazon Command Line Interface? in the Amazon Command Line Interface User Guide.

Note

You can also use an Amazon SNS topic in a different account, but in that case you might need to create a policy for topic that grants access permissions to Amazon Config. For information on granting permissions to an Amazon SNS topic, see Permissions for the Amazon SNS Topic and then go to Creating an IAM Role.

Creating an IAM Role

You can use the IAM console to create an IAM role that grants Amazon Config permissions to access your Amazon S3 bucket, access your Amazon SNS topic, and get configuration details for supported Amazon resources. When you use the console to create an IAM role, Amazon Config automatically attaches the required permissions to the role for you.

Note

If you have used an Amazon service that uses Amazon Config (such as Amazon Security Hub or Amazon Control Tower) and an Amazon Config role has already been created, you should make sure that the IAM role you use when setting up Amazon Config keeps the same minimum privileges as the already created Amazon Config role in order for the other Amazon service to continue to run as expected.

For example, if Amazon Control Tower has an IAM role that allows Amazon Config to read Amazon S3 objects, you should guarantee the same permissions are granted within the IAM role you use when setting up Amazon Config. Otherwise, it may interfere with Amazon Control Tower's operations.

For more information about IAM roles for Amazon Config, see Amazon Identity and Access Management.

To create a role for an Amazon service

  1. Sign in to the Amazon Web Services Management Console and open the IAM console at https://console.amazonaws.cn/iam/.

  2. In the navigation pane of the IAM console, choose Roles, and then choose Create role.

  3. For Select trusted entity, choose Amazon service.

  4. Choose the use case you want for Amazon Config: Config - Customizable, Config - Organizations, Config, or Config - Conformance Packs. Then, choose Next.

  5. On the Name, review, and create page, review the details about your role, and choose Create Role.

To use an Amazon SDK, you must configure it with your credentials. For more information, see The shared config and credentials files in the Amazon SDKs and Tools Reference Guide.

The following code examples show how to create an IAM role.

.NET
Amazon SDK for .NET
Tip

To learn how to set up and run this example, see GitHub.

/// <summary> /// Create a new IAM role which we can attach to a user. /// </summary> /// <param name="client">The initialized IAM client object.</param> /// <param name="roleName">The name of the IAM role to create.</param> /// <param name="rolePermissions">The permissions which the role will have.</param> /// <returns>A Role object representing the newly created role.</returns> public static async Task<Role> CreateRoleAsync( AmazonIdentityManagementServiceClient client, string roleName, string rolePermissions) { var request = new CreateRoleRequest { RoleName = roleName, AssumeRolePolicyDocument = rolePermissions, }; var response = await client.CreateRoleAsync(request); return response.Role; }
  • For API details, see CreateRole in Amazon SDK for .NET API Reference.

Go
SDK for Go V2
Tip

To learn how to set up and run this example, see GitHub.

// CreateRole myRole, err := service.CreateRole(context.Background(), &iam.CreateRoleInput{ RoleName: aws.String(ExampleRoleName), Description: aws.String("My super awesome example role"), AssumeRolePolicyDocument: aws.String(`{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "ec2.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }`), }) if err != nil { panic("Couldn't create role: " + err.Error()) } fmt.Println("☑️ Create Role") fmt.Printf("The new role's ARN is %s \n", *myRole.Role.Arn)
  • For API details, see CreateRole in Amazon SDK for Go API Reference.

Java
SDK for Java 2.x
Tip

To learn how to set up and run this example, see GitHub.

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); }
  • For API details, see CreateRole in Amazon SDK for Java 2.x API Reference.

JavaScript
SDK for JavaScript V3
Tip

To learn how to set up and run this example, see GitHub.

Create the client.

import { IAMClient } from "@aws-sdk/client-iam"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". // Create an IAM service client object. const iamClient = new IAMClient({ region: REGION }); export { iamClient };

Create the role.

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { CreateRoleCommand } from "@aws-sdk/client-iam"; // Sample assume role policy JSON. const role_json = { Version: "2012-10-17", Statement: [ { Effect: "Allow", Principal: { AWS: "USER_ARN", // The ARN of the user. }, Action: "sts:AssumeRole", }, ], }; // Stringify the assume role policy JSON. const myJson = JSON.stringify(role_json); // Set the parameters. const params = { AssumeRolePolicyDocument: myJson, Path: "/", RoleName: "ROLE_NAME" }; const run = async () => { try { const data = await iamClient.send(new CreateRoleCommand(params)); console.log("Success. Role created. Role Arn: ", data.Role.RoleName); } catch (err) { console.log("Error", err); } }; run();
  • For API details, see CreateRole in Amazon SDK for JavaScript API Reference.

PHP
SDK for PHP
Tip

To learn how to set up and run this example, see GitHub.

$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']; }
  • For API details, see CreateRole in Amazon SDK for PHP API Reference.

Python
SDK for Python (Boto3)
Tip

To learn how to set up and run this example, see GitHub.

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
  • For API details, see CreateRole in Amazon SDK for Python (Boto3) API Reference.

Ruby
SDK for Ruby
Tip

To learn how to set up and run this example, see GitHub.

# Creates a role that can be assumed by a user. # # @param role_name [String] The name to give the role. # @param user [Aws::IAM::User] The user who is granted permission to assume the role. # @return [Aws::IAM::Role] The newly created role. def create_role(role_name, user) role = @iam_resource.create_role( role_name: role_name, assume_role_policy_document: { Version: "2012-10-17", Statement: [{ Effect: "Allow", Principal: {'AWS': user.arn}, Action: "sts:AssumeRole" }] }.to_json) puts("Created role #{role.name}.") rescue Aws::Errors::ServiceError => e puts("Couldn't create a role for the demo. Here's why: ") puts("\t#{e.code}: #{e.message}") raise else role end
  • For API details, see CreateRole in Amazon SDK for Ruby API Reference.

Rust
SDK for Rust
Note

This documentation is for an SDK in preview release. The SDK is subject to change and should not be used in production.

Tip

To learn how to set up and run this example, see GitHub.

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()) }
  • For API details, see CreateRole in Amazon SDK for Rust API reference.

You can also use the Amazon Command Line Interface (Amazon CLI) to create an IAM role. For more information, see create-role in the Amazon CLI Command Reference. You can then attach a policy to the role with the attach-role-policy command.

For information about the Amazon CLI, see What is the Amazon Command Line Interface? in the Amazon Command Line Interface User Guide.