前提条件 - AWS Config

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

前提条件

AWS を使用してセットアップする前に AWS CLI、Amazon S3 バケット、Amazon SNS トピック、および前提条件としてポリシーがアタッチされた IAM ロールを作成する必要があります。その後、を使用してのバケット、 AWS CLI トピック、およびロールを指定できます。 AWS Config次の手順に従って、 AWS Configの前提条件をセットアップします。

Amazon S3 バケットを作成する

アカウントに Amazon S3 バケットが既にあり、それを使用する場合は、このステップをスキップして Amazon SNS トピックを作成する に進んでください。

バケットを作成するには
  1. Amazon S3 コンソール (https://console.aws.amazon.com/s3/) を開きます。

  2. [バケットの作成] を選択します。

  3. [バケット名] に、バケットの DNS に準拠する名前を入力します。

    バケット名には次の条件があります。

    • すべての Amazon S3 で一意にする。

    • 3~63 文字で指定する。

    • 大文字を含めないでください。

    • 先頭の文字には小文字の英文字または数字を使用する。

    バケットを作成したら、その名前を変更することはできません。バケット名は、Amazon S3 の既存のバケット名と重複しないように指定してください。バケットの命名ルールと変換の詳細については、「Amazon Simple Storage Service デベロッパーガイド」のバケットの制約と制限を参照してください。

    重要

    バケット名には機密情報を含めないでください。バケット名は、バケット内のオブジェクトを参照する URL に表示されます。

  4. [Region] で、 AWS バケットを配置したいリージョンを選択します。

    レイテンシーとコストを最小化するため、さらに規制条件に対応するために、最寄りのリージョンを選択します。明示的に別のリージョンに移動する場合を除き、特定のリージョンに保管されたオブジェクトは、そのリージョンから移動されることはありません。Amazon S3 AWS リージョンのリストについては、の「AWS サービスエンドポイント」を参照してください。Amazon Web Services 全般のリファレンス

  5. ブロックパブリックアクセスのバケット設定 で、バケットに適用するパブリックアクセスブロック設定を選択します。

    パブリックウェブサイトをホスティングする場合など、ユースケースでオフにする必要のある設定が 1 つ以上あることがわかっている場合を除いて、すべての設定を有効にしておくことをお勧めします。バケットに対して有効にしたパブリックアクセスブロック設定は、バケットに作成するすべてのアクセスポイントに対しても有効になります。パブリックアクセスのブロックの詳細については、「Amazon Simple Storage Service 開発者ガイド」の「Amazon S3 パブリックアクセスブロックの使用」を参照してください。

  6. (オプション) S3 オブジェクトロックを有効にする場合:

    1. [詳細設定] を選択し、表示されるメッセージを読みます。

      重要

      バケットに対する S3 オブジェクトロックは、バケットの作成時にのみ有効にできます。バケットに対してオブジェクトロックを有効にした場合、後で無効にすることはできません。バケットに対してオブジェクトロックを有効にすると、バージョニングも有効になります。バケットに対してオブジェクトロックを有効にした後、バケット内のオブジェクトを保護するには、オブジェクトロック設定を定義する必要があります。オブジェクトの保護の設定の詳細については、「Amazon S3 コンソールを使用した S3 オブジェクトロックの設定」を参照してください。

    2. オブジェクトロックを有効にする場合は、テキストボックスに「enable」と入力し、[確認] を選択します。

    S3 オブジェクトロック機能の詳細については、「Amazon Simple Storage Service 開発者ガイド」の「Amazon S3 オブジェクトロックを使用したオブジェクトのロック」を参照してください。

  7. [バケットを作成] を選択します。

AWS SDK を使用してバケットを作成する場合は、クライアントを作成し、そのクライアントを使用してバケットを作成するリクエストを送信する必要があります。ベストプラクティスとして、クライアントとバケットを同じ AWS リージョンで作成する必要があります。クライアントまたはバケットの作成時にリージョンを指定しない場合、Amazon S3 ではデフォルトのリージョンである米国東部 (バージニア北部) が使用されます。

デュアルスタックのエンドポイントにアクセスするクライアントを作成するには、を指定する必要があります。 AWS リージョン詳細については、Amazon S3 デュアルスタックのエンドポイントを参照してください。使用可能なリストについては AWS リージョン、の「リージョンとエンドポイント」を参照してください。AWS 全般のリファレンス

クライアントを作成すると、リージョンはリージョン固有のエンドポイントにマッピングされます。クライアントは、このエンドポイントを使用して Amazon S3 と通信します。s3.<region>.amazonaws.com。リージョンがローンチされたのが 2019 年 3 月 20 日以降である場合は、クライアントとバケットは同じリージョン内にある必要があります。2019 年 3 月 20 日以前にローンチされたリージョンの場合は、米国東部 (バージニア北部) のリージョンでクライアントを使用することによりバケットを作成できます。詳細については、「レガシーエンドポイント」を参照してください。

AWS これらの SDK コード例は次のタスクを実行します。

  • AWS リージョンを明示的に指定してクライアントを作成する - この例では、クライアントは s3.us-west-2.amazonaws.com エンドポイントを使用して Amazon S3 と通信します。任意の AWS リージョンを指定できます。の一覧については AWS リージョン、『AWS ジェネラルリファレンス』の「リージョンとエンドポイント」を参照してください。

  • バケット名のみを指定してバケット作成リクエストを送信する - クライアントが Amazon S3 にリクエストを送信し、クライアントが作成されたリージョンにバケットを作成します。

  • バケットの場所情報を取得する - Amazon S3 が、バケットの場所情報を、そのバケットに関連付けられている場所のサブリソースに保存します。

Java

この例では、 AWS SDK for Javaを使用して Amazon S3 バケットを作成する方法を示します。有効な Java サンプルを作成してテストする手順については、「Amazon S3 Java コード例のテスト」を参照してください。

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

.NET の実用サンプルを作成およびテストする方法については、「Amazon S3 .NET コード例の実行」を参照してください。

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

有効なサンプルを作成してテストする方法については、「AWS SDK for Ruby の使用 - バージョン 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 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__

AWS Command Line Interface (AWS CLI) を使用して S3 バケットを作成することもできます。詳細については、「AWS CLI コマンドリファレンス」の「create-bucket」を参照してください。

の詳細については AWS CLI、「What is the AWS Command Line Interface?」を参照してください。 『AWS Command Line Interface ユーザガイド』の。

注記

別のアカウントの Amazon S3 バケットを使用することもできますが、 AWS Configに対してアクセス許可を付与するバケットポリシーの作成が必要になる場合があります。Amazon S3 バケットへのアクセス許可を付与する方法については、AWS Config 配信チャネルの Amazon S3 バケットのアクセス許可Amazon SNS トピックを作成する を順に参照してください。

Amazon SNS トピックを作成する

アカウントに Amazon SNS トピックが既にあり、それを使用する場合は、このステップをスキップして「IAM ロールの作成」に進んでください。

Amazon SNS トピックを作成するには
  1. Amazon SNS コンソール (https://console.aws.amazon.com/sns/v3/home) を開きます。

  2. 次のいずれかを行います。

    • これまでにトピックを作成したことがない場合は、ホームページの Amazon SNS の説明をお読みください。 AWS アカウント

    • AWS アカウント 以前にトピックを作成したことがある場合は、ナビゲーションパネルで [Topics] を選択します。

  3. [トピック] ページで、[トピックの作成] を選択します。

  4. [サブスクリプションの作成] ページで [詳細] セクションで、以下を実行します。

    1. [タイプ] で、トピックタイプ (標準またはFIFO) を選択します。

    2. トピックの名前を入力します。FIFO トピックで、名前の末尾に .fifo を追加します。

    3. (オプション) トピックの表示名を入力します。

    4. (オプション) FIFO トピックで、[コンテンツベースのメッセージ重複排除] を選択して、デフォルトのメッセージの重複排除を有効にします。詳細については、「FIFO トピックのメッセージ重複除外」を参照してください。

  5. (オプション) [暗号化] セクションを展開し、以下の操作を実行します。詳細については、「保管時の暗号化」を参照してください。

    1. [暗号化の有効化] を選択します。

    2. カスタマーマスターキー (CMK) を指定します。詳細については、重要な用語を参照してください。

      CMK タイプごとに、[説明]、[アカウント]、および [CMK ARN] が表示されます。

      重要

      CMK の所有者ではない場合、または kms:ListAliases および kms:DescribeKey アクセス権限がないアカウントでログインしている場合、Amazon SNS コンソールで CMK に関する情報は表示できません。

      CMK の所有者に、これらのアクセス権限を付与するよう依頼します。詳細については、「AWS Key Management Service デベロッパーガイド」の「AWS KMS API アクセス権限: アクションとリソースのリファレンス」を参照してください。

      • Amazon SNS (デフォルト) エイリアス/AWS/SNS AWS 用のマネージド CMK がデフォルトで選択されています

        注記

        以下に留意してください。

        • 初めてを使用してトピックの AWS Management Console Amazon SNS AWS のマネージド CMK AWS KMS を指定すると、Amazon SNS AWS 用のマネージド CMK が作成されます。

        • または、SSE Publish が有効になっているトピックで初めてアクションを使用するときに、Amazon SNS AWS 用のマネージド CMK AWS KMS を作成します。

      • AWS アカウントからカスタム CMK を使用するには、カスタマーマスターキー (CMK) フィールドを選択し、リストからカスタム CMK を選択します。

        注記

        カスタム CMK の作成手順については、「AWS Key Management Service デベロッパーガイド」の「キーの作成」を参照してください。

      • AWS AWS 自分のアカウントまたは別のアカウントのカスタム CMK ARN を使用するには、それを [カスタマーマスターキー (CMK)] フィールドに入力します。

  6. (オプション) デフォルトでは、トピックの所有者のみがトピックを発行またはサブスクライブできます。追加のアクセス許可を設定するには、[アクセスポリシー] セクションを展開します。詳細については、「Amazon SNS におけるアイデンティティとアクセス管理」および「Amazon SNS のアクセス制御のケース例」を参照してください。

    注記

    コンソールを使用してトピックを作成すると、デフォルトのポリシーでは aws:SourceOwner 条件キーが使用されます。このキーは aws:SourceAccount に類似しています。

  7. (オプション) 失敗したメッセージ配信試行を Amazon SNS で再試行する方法を設定するには、[配信再試行ポリシー (HTTP/S)] セクションを展開します。詳細については、「Amazon SNS メッセージ配信の再試行」を参照してください。

  8. (オプション) Amazon SNS がメッセージの配信を記録する方法を設定するには CloudWatch、[配信ステータスロギング] セクションを展開します。詳細については、「メッセージの配信ステータスの Amazon SNS アプリケーション属性を使用する」を参照してください。

  9. (オプション) トピックにメタデータタグを追加するには、[タグ] セクションを展開し、[キー] と [] (オプション) に入力し、[タグの追加] を選択します。詳細については、「Amazon SNS トピックのタグ付け」を参照してください。

  10. [Create topic] (トピックの作成) を選択します。

    トピックが作成され、MyTopicページが表示されます。

    トピックの名前ARN、(オプション) 表示名、およびトピックの所有者の AWS アカウント ID が [Details] (詳細) セクションに表示されます。

  11. トピック ARN をクリップボードにコピーします。例:

    arn:aws:sns:us-east-2:123456789012:MyTopic
E メールアドレスを Amazon SNS トピックにサブスクライブするには
  1. Amazon SNS コンソール (https://console.aws.amazon.com/sns/v3/home ) を開きます。

  2. 左のナビゲーションペインで、[サブスクリプション] を選択します。

  3. [サブスクリプション] ページで [サブスクリプションの作成] を選択します。

  4. [サブスクリプションの作成] ページで [詳細] セクションで、以下を実行します。

    1. [トピック ARN] は、トピックの Amazon リソースネーム (ARN) を選択します。

    2. [プロトコル] でエンドポイントタイプを選択します。使用可能なエンドポイントタイプは次のとおりです。

    3. [エンドポイント] に、エンドポイント値 (E メールアドレスや Amazon SQS キューの ARN など) を入力します。

    4. Firehose エンドポイントのみ:サブスクリプションロール ARN には、Firehose デリバリーストリームへの書き込み用に作成した IAM ロールの ARN を指定します。詳細については、「Firehose 配信ストリームを Amazon SNS トピックにサブスクライブするための前提条件」を参照してください。

    5. (オプション) Firehose、Amazon SQS、HTTP/S の各エンドポイントでは、未加工のメッセージ配信を有効にすることもできます。詳細については、「Amazon SNS raw メッセージ配信」を参照してください。

    6. (オプション) フィルターポリシーを設定するには、[サブスクリプションのフィルターポリシー] セクションを展開します。詳細については、「Amazon SNS サブスクリプションフィルターポリシー」を参照してください。

    7. (オプション) サブスクリプションのデッドレターキューを設定するには、Redrive ポリシー (デッドレターキュー) を展開します。詳細については、「Amazon SNS デッドレターキュー (DLQ)」を参照してください。

    8. [サブスクリプションの作成] を選択します。

      コンソールがサブスクリプションを作成し、サブスクリプションの [詳細] ページを開きます。

AWS SDK を使用するには、認証情報を使用して設定する必要があります。詳細については、「AWS SDK とツールのリファレンスガイド」の「共有設定ファイルと認証情報ファイル」を参照してください。

次のコード例は、Amazon SNS トピックを作成する方法を示しています。

.NET
AWS SDK for .NET
注記

まだまだあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

トピックを作成して、個別の名前を付けます。

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

名前と特定の FIFO および重複除外属性を使用して新しいトピックを作成します。

/// <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; }
  • API の詳細については、AWS SDK for .NET API CreateTopicリファレンスのを参照してください

C++
SDK for C++
注記

にはまだまだあります GitHub。用例一覧を検索し、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(); }
  • API の詳細については、AWS SDK for C++ API CreateTopicリファレンスのを参照してください

CLI
AWS CLI

SNS トピックを作成するには

次の create-topic の例では、my-topic という名前の SNS トピックを作成します。

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

出力:

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

詳細については、『AWSコマンドラインインターフェイスユーザーガイド』の「Amazon SQS と Amazon SNS AWS でのコマンドラインインターフェイスの使用」を参照してください。

  • API の詳細については、「AWS CLI コマンドリファレンスCreateTopicのを参照してください。

Go
SDK for Go V2
注記

にはまだまだあります GitHub。用例一覧を検索し、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 }
  • API の詳細については、AWS SDK for Go API CreateTopicリファレンスのを参照してください

Java
SDK for Java 2.x
注記

にはまだまだあります GitHub。用例一覧を検索し、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 ""; } }
  • API の詳細については、AWS SDK for Java 2.x API CreateTopicリファレンスのを参照してください

JavaScript
JavaScript (v3) 用の SDK
注記

にはまだまだあります。 GitHub用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

別のモジュールでクライアントを作成し、エクスポートします。

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({});

SDK モジュールとクライアントモジュールをインポートし、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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScript API CreateTopicリファレンスのを参照してください

Kotlin
SDK for Kotlin
注記

にはまだまだあります GitHub。用例一覧を検索し、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() } }
  • API の詳細については、「AWS SDK for Kotlin API リファレンス」のを参照してくださいCreateTopic

PHP
SDK for PHP
注記

にはまだまだあります。 GitHub用例一覧を検索し、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 for Python (Boto3)
注記

にはまだまだあります GitHub。用例一覧を検索し、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
  • API の詳細については、AWS SDK for Python (Boto3) API リファレンスのを参照してくださいCreateTopic

Ruby
SDK for Ruby
注記

にはまだまだあります。 GitHub用例一覧を検索し、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 for Rust
注記

にはまだまだあります GitHub。用例一覧を検索し、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(()) }
  • API の詳細については、「AWS SDK for Rust API リファレンス」のを参照してくださいCreateTopic

SAP ABAP
SDK for SAP ABAP
注記

にはまだまだあります GitHub。用例一覧を検索し、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.
  • API の詳細については、AWS SDK for SAP ABAP API リファレンスのを参照してくださいCreateTopic

AWS Command Line Interface (AWS CLI) を使用して Amazon SNS トピックを作成することもできます。詳細については、AWS CLI コマンドリファレンスの「create-topic」を参照してください。

の詳細については AWS CLI、「What is the AWS Command Line Interface?」を参照してください。 『AWS Command Line Interface ユーザガイド』の。

注記

別のアカウントの Amazon SNS トピックを使用することもできますが、その場合は、 AWS Configに対するアクセス許可を付与するトピックポリシーの作成が必要になる場合があります。Amazon SNS トピックへのアクセス許可を付与する方法については、Amazon SNS トピックへのアクセス許可IAM ロールの作成 を順に参照してください。

IAM ロールの作成

IAM コンソールを使用して、Amazon S3 バケットへのアクセス、Amazon SNS トピックへのアクセス、 AWS Config およびサポートされているリソースの設定の詳細の取得を行うためのアクセス権限を付与する IAM ロールを作成できます。 AWS コンソールを使用して IAM ロールを作成すると、 AWS Config はロールに必要なアクセス許可を自動的に適用します。

注記

AWS Security Hub や AWS Control Tower AWS AWS Config などを使用するサービスを使用していて、 AWS Config ロールがすでに作成されている場合は、セットアップ時に使用する IAM ロールが、 AWS 他のサービスを期待どおりに実行し続けるために、 AWS Config AWS Config 作成済みのロールと同じ最小権限を保持していることを確認する必要があります。

たとえば、 AWS Control Tower に Amazon S3 AWS Config オブジェクトの読み取りを許可する IAM ロールがある場合は、セットアップ時に使用する IAM ロール内で同じ権限が付与されることを保証する必要があります。 AWS Configそうしないと、 AWS Control Tower の運用に支障をきたす可能性があります。

の IAM ロールの詳細については AWS Config、「AWS Identity and Access Management」を参照してください。

サービスのロールを作成するには AWS
  1. AWS Management Console にサインインし、https://console.aws.amazon.com/iam/ にある IAM コンソールを開きます。

  2. IAM コンソールのナビゲーションペインで、[ロール]、[ロールを作成] を選択します。

  3. [Select trusted entity] (信頼されたエンティティの選択) で、[AWS のサービス] を選択します。

  4. 目的のユースケースを [ AWS Config構成]-[カスタマイズ可能]、[Config]- [Organizations]、[Config]、または [Config-コンフォーマンスパック] から選択します。[次へ] を選択します。

  5. [Name, review, and create] (名前、確認、および作成) ページで、ロールの詳細を確認し、[Create Role] (ロールの作成) を選択します。

AWS SDK を使用するには、認証情報を使用して設定する必要があります。詳細については、「AWS SDK とツールのリファレンスガイド」の「共有設定ファイルと認証情報ファイル」を参照してください。

次のコード例は、IAM ロールを作成する方法を示しています。

.NET
AWS SDK for .NET
注記

まだまだあります GitHub。用例一覧を検索し、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; }
  • API の詳細については、AWS SDK for .NET API CreateRoleリファレンスのを参照してください

Bash
AWS CLI Bash スクリプトを使用
注記

まだまだあります。 GitHub用例一覧を検索し、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 }
  • API の詳細については、「AWS CLI コマンドリファレンスCreateRoleのを参照してください。

C++
SDK for C++
注記

にはまだまだあります GitHub。用例一覧を検索し、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(); }
  • API の詳細については、AWS SDK for C++ API CreateRoleリファレンスのを参照してください

CLI
AWS CLI

例 1: IAM ロールを作成するには

次の create-role コマンドは、Test-Role という名前のロールを作成し、それに信頼ポリシーをアタッチします。

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

出力:

{ "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" } }

信頼ポリシーは、Test-Role-Trust-Policy.json ファイル内で JSON ドキュメントとして定義されます。(ファイル名と拡張子には意味はありません。) 信頼ポリシーはプリンシパルを指定する必要があります。

アクセス許可ポリシーをロールにアタッチするには、put-role-policy コマンドを使用します。

詳細については、「AWS IAM ユーザーガイド」の「IAM ロールの作成」を参照してください。

例 2: 最大セッション期間を指定して IAM ロールを作成するには

次の create-role コマンドは、Test-Role という名前のロールを作成し、最大セッション時間を 7,200 秒 (2 時間) に設定します。

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

出力:

{ "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" } ] } } }

詳細については、『AWS IAM ユーザーガイド』の「ロールの最大セッション期間 (AWS API) の変更」を参照してください。

例 3: タグを使用して IAM ロールを作成するには

次のコマンドは、タグを使用して IAM ロール Test-Role を作成します。この例では、次の JSON 形式のタグを持つ --tags パラメータフラグを使用します: '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'。あるいは、--tags フラグを次の短縮形式のタグとともに使用することもできます: '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"}'

出力:

{ "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" } ] } }

詳細については、「AWS IAM ユーザーガイド」で「IAM ロールのタグ付け」を参照してください。

  • API の詳細については、「AWS CLI コマンドリファレンスCreateRoleのを参照してください。

Go
SDK for Go V2
注記

にはまだまだあります GitHub。用例一覧を検索し、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 }
  • API の詳細については、AWS SDK for Go API CreateRoleリファレンスのを参照してください

Java
SDK for Java 2.x
注記

にはまだまだあります GitHub。用例一覧を検索し、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); } }
  • API の詳細については、AWS SDK for Java 2.x API CreateRoleリファレンスのを参照してください

JavaScript
JavaScript (v3) 用の SDK
注記

にはまだまだあります。 GitHub用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

ロールを作成します。

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); };
  • API の詳細については、AWS SDK for JavaScript API CreateRoleリファレンスのを参照してください

PHP
SDK for PHP
注記

にはまだまだあります GitHub。用例一覧を検索し、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']; }
  • API の詳細については、AWS SDK for PHP API CreateRoleリファレンスのを参照してください

Python
SDK for Python (Boto3)
注記

にはまだまだあります GitHub。用例一覧を検索し、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
  • API の詳細については、AWS SDK for Python (Boto3) API リファレンスのを参照してくださいCreateRole

Ruby
SDK for Ruby
注記

にはまだまだあります。 GitHub用例一覧を検索し、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
  • API の詳細については、AWS SDK for Ruby API CreateRoleリファレンスのを参照してください

Rust
SDK for Rust
注記

にはまだまだあります GitHub。用例一覧を検索し、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()) }
  • API の詳細については、「AWS SDK for Rust API リファレンス」のを参照してくださいCreateRole

Swift
SDK for Swift
注記

これはプレビューリリースの SDK に関するプレリリースドキュメントです。このドキュメントは変更される可能性があります。

注記

にはまだまだあります GitHub。用例一覧を検索し、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 } }
  • API の詳細については、『AWS SDK for Swift API リファレンス』のを参照してくださいCreateRole

AWS Command Line Interface (AWS CLI) を使用して IAM ロールを作成することもできます。詳細については、「AWS CLI コマンドリファレンス」の create-role を参照してください。その後、attach-role-policyコマンドを使用してポリシーをロールにアタッチできます。

の詳細については AWS CLI、「What is the AWS Command Line Interface?」を参照してください。 『AWS Command Line Interface ユーザガイド』の。